【问题标题】:change label text of parent form from child form [duplicate]从子表单更改父表单的标签文本[重复]
【发布时间】:2012-11-20 18:05:46
【问题描述】:

可能重复:
accessing controls on parentform from childform

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

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

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

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    在调用子窗体时,像这样设置子窗体对象的Parent属性..

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

    在您的父表单上,将标签文本的属性设置为 as..

    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; 时显示错误“无法将顶级控件添加到控件中。”
    【解决方案2】:

    毫无疑问,有很多捷径可以做到这一点,但在我看来,一个好的方法是从子表单中引发一个事件,请求父表单更改显示的文本。父窗体应在创建子窗体时注册此事件,然后可以通过实际设置文本来响应它。

    所以在代码中它看起来像这样:

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

    它有点冗长,但它使您的孩子形式与对其父母的任何知识脱钩。这是一个很好的可重用模式,因为这意味着子表单可以在另一个主机(没有标签)中再次使用而不会中断。

    【讨论】:

      【解决方案3】:

      试试这样的:

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

      【讨论】:

      • 是否需要创建父表单的新对象?
      • 我应该从我的子表单创建父表单的新对象,然后使用该新对象访问标签控件吗?
      • @Milind,当然不是,您必须将父表单(form1)作为子表单(test1)的所有者传递,然后从子表单中使用它们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多