The traditional way
Create a public data resource class to store the value of Form 2's TextBox:
public class ComValue { public static string Txtvalue { get; set; } }
Code for Form 1:
private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); }
//Use timer to keep copying label2 private void timer1_Tick(object sender, EventArgs e) { label2.Text = ComValue.Txtvalue; }
Code for Form 2:
private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); } private void timer1_Tick(object sender, EventArgs e) { label2.Text = ComValue.Txtvalue; }
This way consumes resources by using the timer.
Second, use the delegate to pass the value, and pass the method of assigning form1 to lable2 to form2
Code for Form 1:
private void button1_Click(object sender, EventArgs e) {
//Pass SetValue to Form2 and let Form2 execute this method Form2 f2 = new Form2(SetValue); f2.Show(); } //Method of assigning value to label2 void SetValue(string str) { label2.Text = str; }
Code for Form 2:
public delegate void del(string str); private del de1; public Form2 (del del) { this.de1 = del; InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.de1.Invoke(textBox1.Text.Trim());//The final execution here is the SetValue function of Form 1 }
Form interface and execution result: