Pass values between forms, and pass values between forms
Click button event in the Form1 form:
Private void button#click (object sender, EventArgs e) {// Method 1: Pass the current Form as an object to the show Form frm = new Form2 (); frm. owner = this; frm. show ();
}
Form load loading events and Button clicking events in Form2
Private void Form2_Load (object sender, EventArgs e) {Form1 frm = (Form1) Owner; foreach (var ff in frm. controls) {if (ff is TextBox) {this. textBox1.Text = (ff as TextBox ). text ;}} private void button#click (object sender, EventArgs e) {// method 1 // receives the passed form object, find the control on the form and assign the value Form1 frm = (Form1) Owner; foreach (System. windows. forms. control ff in frm. controls) // traverse all Controls passed over the form {if (ff is TextBox) // if the control is of the TextBox type {// if (ff. name. equals ("textBox1") if multiple text boxes exist, you can also go to name (ff as TextBox ). text = this. textBox1.Text ;}}
}
This transfer is mostly used to pass the current form as an object to another transfer and use the value of the control in the current form, in the Form2 form displayed in show, you can directly modify the value of the control of the Form1 form.
Method 2: PASS Parameters in the Form class and receive parameters in the constructor of the show form.
Click Event in Form1
Private void button#click (object sender, EventArgs e) {// Method 2: Pass the string txt = this parameter in the Form class. textBox1.Text; Form frm = new Form2 (txt); frm. owner = this; frm. show ();
}
Receiving parameters of constructors in Form2
Public Form2 (string txt) {this. textBox1.Text = txt; InitializeComponent ();
}
This method does not need to be used to pass the value back to the first form.
The third method is to write a class, declare static variables, and then accept and pass the value. This method is quite common and you don't need to repeat it here.
The fourth method is to declare a delegate and an event.
Declare the delegate and event in the Form2 form
Public delegate void getTextdelegate (string text); // defines the global
Public static event getTextdelegate TextCool; // defines the event to be written in the class and can be called directly using the form name.
Private void button#click (object sender, EventArgs e) {if (TextCool! = Null) {TextCool (this. textBox1.Text );
}
}
Call in Form1 form
Private void button#click (object sender, EventArgs e) {Form2 frm = new Form2 (); Form2.TextCool + = Form2_TextCool; frm. show ();} void Form2_TextCool (string text) {this. textBox1.Text = text ;}
You can upload the value back to Form1 in Form2. In the defined delegate, the value belongs to the string type, and the object type can be used. Then you can pass the value we want to transfer.