保持控件私有,因此只能从创建的表单访问它们。使用表单的引用来访问某个表单。我将在按下按钮时(在每个表单中)向您展示如何更简单地将数据从表单传递到表单:
class Form1
{
Form2 f2;
private void buttonOpenForm2_Click(object sender, EventArgs e)
{
f2 = new Form2(this);
f2.Show();
}
private void SayHiOnForm2_Click(object sender, EventArgs e)
{
if(f2 != null)
f2.DataFromForm2("Hello from form 1.");
else
MessageBox.Show("Form2 is not yet opened.");
}
public void DataFromForm2(stirng message)
{
this.label1.Text = message;
}
}
//on form2:
class Form2
{
Form1 f1;
public Form2(Form1 _f1)
{
InitilaizeComponent();
this.f1 = _f1;
}
private void SayHiOnForm1_Click(object sender, EventArgs e)
{
f1.DataFromForm2("Hello from form 2.");
}
public void DataFromForm1(stirng message)
{
this.label1.Text = message;
}
}
如果你愿意,你甚至可以使用事件。它更整洁,但这也可以。