可能的重复:
从childform访问parentform上的控件
我有一个父窗体form1和一个子窗体test1,我想从子窗体更改父窗体的标签文本,在我的父窗体中,我有一个显示结果的方法。
public void ShowResult()
{ label1.Text="hello"; }
我想在子窗体test1的按钮单击事件中更改label.Text="Bye";
。请给出任何建议。
可能的重复:
从childform访问parentform上的控件
我有一个父窗体form1和一个子窗体test1,我想从子窗体更改父窗体的标签文本,在我的父窗体中,我有一个显示结果的方法。
public void ShowResult()
{ label1.Text="hello"; }
我想在子窗体test1的按钮单击事件中更改label.Text="Bye";
。请给出任何建议。
在调用子窗体时,需要设置子窗体对象的Parent
属性,方法如下:
Test1Form test1 = new Test1Form();
test1.Show(this);
public string LabelText
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}
((Form1)this.Owner).LabelText = "Your Text";
public delegate void RequestLabelTextChangeDelegate(string newText);
public partial class Form2 : Form
{
public event RequestLabelTextChangeDelegate RequestLabelTextChange;
private void button1_Click(object sender, EventArgs e)
{
if (RequestLabelTextChange != null)
{
RequestLabelTextChange("Bye");
}
}
public Form2()
{
InitializeComponent();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.RequestLabelTextChange += f2_RequestLabelTextChange;
}
void f2_RequestLabelTextChange(string newText)
{
label1.Text = newText;
}
}
这种方式有点冗长,但它将子表单与其父表单的任何知识解耦。这是一种良好的重用模式,因为这意味着子表单可以在另一个没有标签的主机中再次使用而不会出现问题。
Test1Form test1 = new Test1Form();
test1.Show(form1);
((Form1)test1.Owner).label.Text = "Bye";
Test1Form test1 = new Test1Form(); test1.Parent = this;
时,会显示错误信息 "无法将顶级控件添加到控件中。"。 - Milind