Summary of passing values between windows Forms
After passing values between windows Forms, I have summarized four methods: global variables, attributes, form constructors, and delegate.
The first global variable:
This is the simplest, as long as the variable is described as static, and the form1 variable is directly referenced in form2. The Code is as follows:
Define a static variable public static int I = 9 in form1;
The buttons in Form2 are as follows:
Private void button#click (object sender, System. EventArgs e)
{
TextBox1.Text = Form1. I. ToString ();
}
The second method is to use attributes. For details, see my blog:
Http://blog.csdn.net/tjvictor/archive/2006/06/04/772711.aspx
The third method is to use constructor:
The button of Form1 is written as follows:
Private void button#click (object sender, System. EventArgs e)
{
Form2 temp = new Form2 (9 );
Temp. Show ();
}
The Form2 constructor is written as follows:
Public form2 (int I)
{
Initializecomponent ();
Textbox1.text = I. tostring ();
}
The fourth method is to use delegate. The Code is as follows:
Form2 first defines a delegate
Public Delegate void returnvalue (int I );
Public returnvalue;
The code for the button in form2 is as follows:
Private void button#click (Object sender, system. eventargs E)
{
If (returnvalue! = NULL)
Returnvalue (8 );
}
The buttons in form1 are as follows:
Private void button#click (Object sender, system. eventargs E)
{
Form2 temp = new form2 ();
Temp. ReturnValue = new temp. Form2.returnvalue (showvalue );
Temp. Show ();
}
Private void showvalue (int I)
{
TextBox1.Text = I. ToString ();
}
Click the button of form2 to change the value in the textbox of form1.
In the four methods,
The first one is two-way data transfer. That is to say, if form1 and form2 change the I value, the other party will also be affected.
The second method can be unidirectional or bidirectional value transfer.
The third method is form1-> form2 unidirectional value transfer.
The fourth method is form2-> form1 one-way pass value.
I will add a new method in the future. Another method is to use event, which is similar to delegate. I will not talk about it here.
Trackback: http://tb.blog.csdn.net/TrackBack.aspx? PostId = 824617