从子窗体更改父窗体的标签文本

3

可能的重复:
从childform访问parentform上的控件

我有一个父窗体form1和一个子窗体test1,我想从子窗体更改父窗体的标签文本,在我的父窗体中,我有一个显示结果的方法。

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

我想在子窗体test1的按钮单击事件中更改label.Text="Bye";。请给出任何建议。

3个回答

8

在调用子窗体时,需要设置子窗体对象的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";

((Form1)this.ParentForm)之后,label1不可访问。 - Milind
我在父窗体中使用了labelText属性,现在在子窗体中可以访问它,但在运行时会抛出异常“对象引用未设置为对象的实例”。 - Milind
在调用子窗体 Test1Form test1 = new Test1Form(); test1.Parent = this; 时,会显示错误信息 "无法将顶级控件添加到控件中。"。 - Milind
@Milind 好的,不用管它,使用窗体的 Owner 属性,并将子窗体命名为 test1.Show(this); - Talha
关键是在 Show 中加入 "this":test1.Show(this); - Jarkid

6
毫无疑问,有很多捷径可以完成这个任务,但在我看来,一个好的方法是从子窗体中引发事件,要求父窗体更改显示的文本。当创建子窗体时,父窗体应该注册此事件,并能够通过实际设置文本来响应它。
因此,在代码中,它会类似于这样:
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;
    }
}  

这种方式有点冗长,但它将子表单与其父表单的任何知识解耦。这是一种良好的重用模式,因为这意味着子表单可以在另一个没有标签的主机中再次使用而不会出现问题。


0
尝试像这样做:

Test1Form test1 = new Test1Form();
test1.Show(form1);

((Form1)test1.Owner).label.Text = "Bye";

需要创建父窗体的新对象吗? - Milind
我应该在子窗体中创建父窗体的新对象,然后使用该新对象访问标签控件吗? - Milind
@Milind,当然不是,你必须将父窗体(form1)作为子窗体(test1)的所有者传递,然后从子窗体中使用它们。 - Hamlet Hakobyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接