使用属性在两个表单之间传递数据
我在C#中的两个窗体之间传递数据。 Form1是主窗体,其文本框将接收从form2_textbox传递给它的文本,并将其显示在其文本框(form1_textbox)中。
首先,打开form1,使用空文本框和按钮,在单击form1_button时,将打开form2。 在Form2中,我在form2_textbox中输入了一个文本,然后单击了按钮(form2_button)。单击此按钮的事件,它将文本发送到form1的文本框,并且form1将以其空的form1_textbox与从form2接收的文本聚焦。
我正在使用属性来实现此任务。 FORM2.CS
public partial class Form2:Form {//声明事件forms2公共事件EventHandler SomeTextInSomeFormChanged;
public Form2() { InitializeComponent(); } public string get_text_for_Form1 { get { return form2_textBox1.Text; } } //On the button click event of form2, the text from form2 will be send to form1: public void button1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); f1.set_text_in_Form1 = get_text_for_Form1; //if subscribers exists if(SomeTextInSomeFormChanged != null) { SomeTextInSomeFormChanged(this, null); } } }
Form1.cs的
public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string set_text_in_Form1 { set { form1_textBox1.Text = value; } } private void form1_button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged); } //in form 1 subcribe to event Form2 form2 = new Form2(); public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e) { this.Focus(); } }
在form2中,您需要创建事件并在form1中订阅它。 就这样。
//declare event in form 2 public event EventHandler SomeTextInSomeFormChanged; // call event in form2 text_changed event if(SomeTextInSomeFormChanged != null) SomeTextInSomeFormChanged(this, null); //in form 1 subcribe to event var form2 = new Form2(); form2.SomeTextInSomeFormChanged += SomeHandlerInForm1WhereYouCanSetForcusInForm1
更新:
窗体2:
public Form2() { InitializeComponent(); } public void button1_Click(object sender, EventArgs e) { //if subscribers exists if(SomeTextInSomeFormChanged != null) { SomeTextInSomeFormChanged(form2_textBox1, null); } }
Form1中:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void form1_button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged); } public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e) { var textBoxFromForm2 = (TextBox)sender; form1_textBox1.Text = textBoxFromForm2.Text this.Focus(); } }
下面列出的网站有很好的教程。 这个特定页面演示了如何实现这一目标:
那这个呢。
((Form2)Application.OpenForms["Form2"]).textBox1.Text = "My Message";