經常使用的Winform窗體傳值有兩種方式。this
1.更改Form.designer.cs文件,將控件的設爲Public,供子窗體訪問。spa
在designer.cs文件的最後,找到你的控件聲明。code
private System.Windows.Forms.TextBox textBox1;
更改Private爲public,保存便可。orm
2.利用委託進行窗體傳值。blog
父窗體:Form1事件
子窗體:Form2string
點擊Form1,彈出Form2,點擊按鈕返回值給Form1it
首先在Form2中定義委託和事件:event
//聲明委託 和 事件 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中進行調用:form
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; } }