2012-11-20 168 views
2

可能重复:
accessing controls on parentform from childform更改标签文本

我已经父窗体Form1和子窗体TEST1我想改变孩子父窗体标签文本形式在我的父母形式我有方法showresult()

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

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

调用子窗体时

回答

7

,设置子窗体对象的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"; 
+0

'((Form1)this.ParentForm)''在那个label1不可访问之后 – Milind

+0

@Milind检查更新的答案 – Talha

+0

我在父窗体中使用labelText属性,它现在可以在子窗体中访问,但是在运行时它会抛出异常“Object引用未设置为对象的实例“。 – Milind

0

尝试这样的:

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

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

是否需要创建父窗体的新对象? – Milind

+0

@Milind你是什么意思? –

+0

从我的子窗体应创建父窗体的新对象,然后访问标签控件与新对象? – Milind

4

毫无疑问,有很多的快捷方法可以做到这一点,但在我看来,一个好的办法是提高从请求父形式变化子窗体的事件显示的文字。父表单应该在创建孩子时注册此事件,然后可以通过实际设置文本对其进行响应。

所以在代码,这将是这个样子:

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; 
    } 
} 

它多一点长篇大论,但是从有其父的任何知识它去将你的子窗体。这对于可重用性来说是一个很好的模式,因为它意味着子表单可以在没有中断的情况下在另一个主机(没有标签)中再次使用。