C# winform窗體傳值 利用委託 子窗體傳值給父窗體
阿新 • • 發佈:2018-11-28
首先在Form2中定義委託和事件:
//宣告委託 和 事件 public delegate void TransfDelegate(String value); public partial class Form2 : Form { public Form2() { InitializeComponent(); } public event TransfDelegate TransfEvent; private void button1_Click(object sender, EventArgs e) { //觸發事件 TransfEvent(textBox1.Text); this.Close(); } }
然後在Form1中進行呼叫:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(); //註冊事件 frm.TransfEvent += frm_TransfEvent; frm.ShowDialog(); } //事件處理方法 void frm_TransfEvent(string value) { textBox1.Text = value; } }