表單之間傳值

表單之間傳值方式: 

一、使用建構子
二、使用方法委託
三、使用傳址方式

三、使用傳址方式
先建立一個專案
設定Form1畫面


設定Form2畫面


在Form1 設定如下:
namespace databtwforms
{
    public partial class Form1 : Form
    {
        public static Form1 instance;
        public TextBox tb1;
        public Form1()
        {
            InitializeComponent();
            instance = this;
            tb1 = this.textBox1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.Show();  
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2.instance.lab1.Text = textBox2.Text;  //從Form1傳值給Form2
        }
    }
}
在Form2 設定如下:
namespace databtwforms
{
    public partial class Form2 : Form
    {
        public static Form2 instance; //新增一個靜態的實例
        public Label lab1;
        public Form2()
        {
            InitializeComponent();
            instance = this; //將Form2 指向instance
            lab1 = label1; //將畫面上label1也指 lab1
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form1.instance.tb1.Text = "set by form2"; //從Form2傳值給Form1
} } }
執行結果:


留言