如何从第二种形式的值更新活动窗体表单文本框?

时间:2016-07-06 16:05:17

标签: c# forms winforms

我有一个Windows窗体(让我们称之为Form1)打开第二个窗体(Form2),以便用户从组合框中选择一些内容。

// 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();
}

在comboBox中选择一个项目后,用户点击“更新”按钮,使用所选值更新textBox中的Form1

private void updateForm1(object sender, EventArgs e)
    {
        // Form1.textBox1 is not accessible
    }

我知道如何将值从Form1传递到Form2,但如何将值从Form2传递回有效Form1?我无法在不重新创建表单的情况下访问活动Form1

1 个答案:

答案 0 :(得分:0)

我通过传递事件处理程序找到了答案。

// 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();
}