页面间传值的⑤种方法

5、构造函数传值

第一步 在调用窗体建立构造函数 写入参数ex:

public Form2(Sting msg):this()  //调用无参的构造函数

{

label1.text=msg

}

第二步 传值窗体构造调用窗体的实例 ex:

string txtMsg=textBox1.text;

Form2   frm2 = new Form2(txtMsg);

1、属性传值

1、传值窗体定义属性
public ChildrenFrm MSg { get; set; }  //子窗体类型的属性

2、private void ParentFrm_Load(object sender, EventArgs e)
        {
            ChildrenFrm chFrm = new ChildrenFrm();
            MSg = chFrm; //此对象直接赋予给需要传值窗体类型属性
            chFrm.Show();
        
        }

//注意更改接收窗体控件的属性值为Public

3private void btnMsg_Click(object sender, EventArgs e)
        {
            MSg.txtMsg.Text = this.txtMsg.Text;
         

        }

2、方法传值

1、传值窗体定义属性
 public ChildrenFrm MSg { get; set; }
2、private void ParentFrm_Load(object sender, EventArgs e)
        {
            ChildrenFrm chFrm = new ChildrenFrm();
            MSg = chFrm; //此对象直接赋予给需要传值窗体类型属性
            chFrm.Show();
         
        }

 3、 private void btnMsg_Click(object sender, EventArgs e)
        {
            MSg.StrText(this.txtMsg.Text);
           
        } //注意方法调用接收窗体方法
1、  public void StrText(string txt)
        {
         
            this.txtMsg.Text = txt;
        } 

  

3、委托传值

1、主窗体创建委托泛型集合属性
  public Action<string> ShowMsg {get;set;}  //委托类型
2、 private void ParentFrm_Load(object sender, EventArgs e)
        {      
            Children2 chFrm2 = new Children2();
            ShowMsg += chFrm2.Say;//注意此处对象点传值窗体的方法
            chFrm2.Show();
        }
3、 private void btnMsg_Click(object sender, EventArgs e)
        {
           
            ShowMsg(this.txtMsg.Text);

        }

接收窗体方法
1、  public void Say(string txt)
        {
            this.txtMsg.Text = txt;
        }

//事件传值(最优的选择)事件是委托类型的特殊实例,事件触发只能在类的内部触发

1、定义事件

 public event EventHandler ShowMsgStr; 

2、触发事件

ShowMsgStr(this,new ChangeMsg(){txt=this.txtmsg.text});//this指当前窗体对象;属性初始化器定义类型属性的值

2.1定义新类继承与EventArgs

public class ChangeMsg:EvenArgs

{

public string txt{get;set;}

}

3、主窗体发布事件

ChildrenFrm chFrm = new ChildrenFrm();//传值窗体对象
            //事件方式
            ShowMsgStr += chFrm.AfterMsg;  //与委托类似传值窗体对象调用子窗体的方法
            chFrm.Show();

4、子窗体调用

1、定义方法传值

public void StrText(string txt)
        {
           
            this.txtMsg.Text = txt;
        }

   public void AfterMsg(object sender, EventArgs e)
        {
            ChangeMsgEvent ch = e as ChangeMsgEvent; //把 父类转换为子类使用
            this.StrText(ch.Txt);//调用当前窗体的方法传入值
        }

原文地址:https://www.cnblogs.com/haimingkaifa/p/5329866.html