更改子窗体中的label.text [英] change label.text in children form

查看:103
本文介绍了更改子窗体中的label.text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我有两种Windows形式:form1form2
我想在单击form2中的按钮时更改 form1中的label.text.当关闭form2时,我需要label.text不变.
我在form1中编写了一个公共方法,但这不能更改label.text
我该怎么办????

Hi to all
I have two Windows form : form1 and form2
I want label.text in form1 change when I click in button in form2 .when close form2 I need label.text not change.
I write a public method in form1 but this can''t change label.text
How can I do this ????

推荐答案

最好的方法是让Form2通知一个事件,该事件由Form1处理并通过form2中的公共属性获取新数据. .这样,Form2不需要任何有关Form1的信息,而Form1仅在对它感兴趣时才需要获取数据.

在子窗体中:

The best way is for Form2 to signal an event which Form1 handles and gets the new data via a public property in form2. That way, Form2 need no nothing about Form1, and Form1 need only get teh data if it is actually interested in it.

In the child form:

public partial class frmChild : Form
   {
   // Signal file change happened
   public event EventHandler Changed;

   protected virtual void OnChanged(EventArgs e)
      {
      EventHandler eh = Changed;
      if (eh != null)
         {
         eh(this, e);
         }
      }

   private void DoSomethingToChangeData()
      {
      OnChanged(null);
      }
   }


-----给eh的指示是如果处理程序在空检查之间进行更改
-----和执行.
-----(不太可能,但可能)

-----空检查是为了确保有处理程序.如果不是,最好
-----优雅地忽略它,而不是依靠抛出的异常
-----(NullReferenceException)

在家长表格中:


----- The asign to eh is in case the handler changes between null check
----- and exec.
----- (unlikely, but possible)

----- The null check is to ensure there is a handler. If not, better to
----- ignore it gracefully, than to rely on the thrown exception
----- (NullReferenceException)

In the Parent form:

public frmParent()
    {
    frmChild.Change += new frmChange.ChangeHandler(Changed);
    }

private void ShowChildForm()
    {
    // Link in his event so if it changes, we detect it.
    frmChild fd = new frmChild();
    fd.ShowDialog();
    }

//
// Fired when the data is changed at a lower level.
//
private void Changed(object sender, EventArgs e)
    {
    Form2 f = sender as Form2;
    if (f != null)
        {
        myLabel.Text = f.Data;
        }
    }


public frmParent()
     {
     frmChild.Change += new frmChange.ChangeHandler(Changed);
     }

 private void ShowChildForm()
     {
     // Link in his event so if it changes, we detect it.
     frmChild fd = new frmChild();
     fd.ShowDialog();
     }

 //
 // Fired when the data is changed at a lower level.
 //
 private void Changed(object sender, EventArgs e)
     {
     Form2 f = sender as Form2;
     if (f != null)
         {
         myLabel.Text = f.Data;
         }
     }


这篇关于更改子窗体中的label.text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆