Data transfer between WinForm forms is an essential technology for development, and several typical methods of passing values are described below
1, the value of the constructor, but this method is one-way (recommended)
On the code, first pass the value
Private void button2_click (object sender, EventArgs e) { new Form3 (" the value to pass. " ); FR3. ShowDialog (); }
The value is, yes, you need to overload a Form3 constructor, and then show the value you got.
Public FORM3 (string Canshu) { InitializeComponent (); = Canshu; }
, it's so simple
2, static variable transfer value (not recommended)
Static variables can be declared where you need them, such as a single class, or a form, as we declare here in Form2
Public Static string xvalue;
Private void button2_click (object sender, EventArgs e) { " the value to be passed Xvalue "; New Form3 (); FR3. ShowDialog (); }
Assign the value first, then the value in the FORM3
Public Form3 () { InitializeComponent (); = Form2.xvalue; // Form2 is actually a class, take the static value directly, if the static variable Xvalue defined in other classes, will be Form2 to replace it }
On
3. Pass value by common attribute
First create a common property in the form you want to open, and then assign a value in the call window. For example, the following Form2 start Form3, that is, to Form3 yvalue value
(1) Defining common attributes in FORM3
Public string yvalue { get { return Label1. Text.tostring (); } Set { = value; } }
(2) Start the FORM3 in Form2 and pass the value
Private void button2_click (object sender, EventArgs e) { new Form3 (); " the value to pass. " ; FR3. ShowDialog (); }
4. Pass the value through the Owner property
(1) Declare a public variable in caller Form2 and assign a value to set the owner of the Form3 that needs to be started
Public string Xvalue; Private void button2_click (object sender, EventArgs e) { "Form2 value to pass" "; New Form3 (); This ; FR3. ShowDialog (); }
(2) Starting the form FORM3 value
Private void Form3_load (object sender, EventArgs e) { = (Form2)this. Owner; = fr2.xvalue; }
This method actually passes Form2 to FORM3, so FORM3 can take all the public variables and properties of Form2.
5. Transfer value (recommended)
Delegate event passing value is mainly used in the subform to the parent form on the value, that is, the above Form3 to Form2 value
(1) Declare the Commission event in FORM3 first
Public Delegate void Puthandler (string text); Public Puthandler Puttexthandler; // Delegate Object Private void button1_click (object sender, EventArgs e) { ifnull ) { Puttexthandler (textBox1.Text.ToString ()); } }
(2) Binding delegate events in Form2
Public void getValue (string strv) { this. TextBox1.Text = strv; } Private void button1_click (object sender, EventArgs e) { new FORM3 (); = GetValue; FR3. ShowDialog (); }
Of course, there are other ways to pass the value, but also interested friends can be studied.
WinForm development of the form pass value