[英]How to update an active windows form textbox from a value in a second form?
I have a Windows Form (let's call it Form1
) that opens a second windows form ( Form2
) to make the user select something from a comboBox. 我有一个Windows窗体(我们称它为Form1
),它可以打开第二个Windows窗体( Form2
),以使用户从comboBox中选择内容。
// create form1
var Form1 = new Form1();
Form1.Show();
// event to open form2
private void openForm2(object sender, EventArgs e)
{
Form2 Form2= new Form2();
Form2.Show();
}
After selecting an item in the comboBox, the user clicks on the "Update" button to update a textBox
in Form1
with the selected value. 在comboBox中选择一个项目后,用户单击“更新”按钮以使用所选值更新Form1
的textBox
。
private void updateForm1(object sender, EventArgs e)
{
// Form1.textBox1 is not accessible
}
I know how to pass a value from Form1
to Form2
, but how can I pass a value from Form2
back to the active Form1
? 我知道如何将值从Form1
传递到Form2
,但是如何将值从Form2
传递回活动的Form1
? I can't access the active Form1
without recreating the form. 如果不重新创建表单,我将无法访问活动的Form1
。
I found the answer by passing an event handler. 我通过传递事件处理程序找到了答案。
// propertie in form1 to hold the form2 instance to get the value back
private Form2 _form2;
public Form2 form2
{
get { return _form2; }
set { this._form2= value; }
}
// opens the form1
var Form1 = new Form1();
Form1.Show();
// event to open form2
private void openForm2(object sender, EventArgs e)
{
Form2 Form2= new Form2();
Form2.FormClosing += new FormClosingEventHandler(getValueFromForm2);
Form2.Show();
this.form2 = Form2;
}
// event to retrieve the value and update textbox of form1
private void getValueFromForm2(object sender, FormClosingEventArgs e)
{
Control ctrl = this.form2.Controls.Find("theControlWithTheValue", true)[0];
// control is a listbox
ListBox lbox = ctrl as ListBox;
// update form1 textbox
textBoxInForm1.Text = lbox.SelectedItem.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.