从子表单更改父表单的标签文本

可能重复:
从子窗体访问父窗体上的控件

我有父表单form1和子表单test1我想在父表单中从子表单更改父表单的标签文本我有showresult()的方法

public void ShowResult() { label1.Text="hello"; }

我想改变label.Text="Bye"; 在按钮点击事件上形成我的子表单test1。 请提出任何建议。

在调用子表单时,像这样设置子表单对象的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; } } 

它的啰嗦有点长,但它将你的孩子forms与其父母的任何知识分开。 这是一个很好的可重用性模式,因为它意味着子表单可以在另一个主机(没有标签)中再次使用而不会中断。

尝试这样的事情:

 Test1Form test1 = new Test1Form(); test1.Show(form1); ((Form1)test1.Owner).label.Text = "Bye";