Passing data between C # two Windows
1 Common variable Value passing
public partial class Form1:form //parent Form {public string name= ""; Public Form1 () { InitializeComponent (); } private void Newbtn_click (object sender, EventArgs e) { Form2 Form2 =new Form2 (); Form2. ShowDialog (); NOTE this! Must is ShowDialog () not Show ()! if (Form2. DialogResult = = DialogResult.OK) { TextBox1.Text = form2.name; Form2. Close ();}} }
public partial class Form2:form//son Form {public string name { set {TextBox1.Text = value;} get {return textbox1.text;} } Public Form2 () { InitializeComponent (); } private void OK_Click (object sender, EventArgs e) { if (TextBox1.Text = = "") { MessageBox.Show (" Input! "); return; } DialogResult = DialogResult.OK; Close (); } }
2 Delivery using address mode
public partial class Form1:form //parent Form {public string name= ""; Public Form1 () { InitializeComponent (); } private void Newbtn_click (object sender, EventArgs e) { Form2 Form2 =new Form2 (); Form2. The pointer to Owner = This;//form2 points to Form1 Form2. ShowDialog (); TextBox1.Text = Form2.name; Form2. Close (); } }
public partial class Form2:form //son Form {public string name { set {TextBox1.Text = value;} get {return textbox1.text;} } Public Form2 () { InitializeComponent (); } private void OK_Click (object sender, EventArgs e) { if (TextBox1.Text = = "") { MessageBox.Show (" Input! "); return; } Form1 Form1 = (Form1) this. Owner;//form2 's parent window pointer is assigned to Form1 Close ();} }
Passing data between C # windows