在winForm 中实现两个窗体间的数据传递(转自Codeproject)


一共有4种实现方法
  1. Using constructor
  2. Using objects
  3. Using properties
  4. Using delegates

这里主要介绍方法3、4
方法3:

Step 1: Add a property in form1 to retrieve value from textbox.

 

public   string  _sendtxt
        {
            
get { return   this .txtBox1.Text.ToString().Trim();}
        }


Step 2: Add a property in form2 to set the labels’ text

 

public   string  _recevicetxt
        {
            
set  {  this .label1.Text = value; }
        }


Step 3:
In form1’s button click event handler add the following code.

private   void  btnsend_Click( object  sender, EventArgs e)
        {
            Form2 frm2 
=   new  Form2();
            frm2.Show();
            frm2._recevicetxt 
=  _sendtxt;
        }

方法4:

Step 1: Add a delegate signature to form1 as below

         public   delegate   void  delPassData(TextBox text);


Step 2: In form1’s button click event handler instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below

private   void  btnsend_Click( object  sender, System.EventArgs e)
        {
            Form2 frm 
=   new  Form2();
            delPassData del 
=   new  delPassData(frm.funData);
            del(
this .textBox1);
            frm.Show();
        }

 

Step 3: In form2, add a function to which the delegate should point to. This function will assign textbox’s text to the label.

 

public   void  funData(TextBox txtForm1)
        {
            label1.Text 
=  txtForm1.Text;
        }


详细介绍请参考:http://www.codeproject.com/useritems/pass_data_between_forms.asp

FrmM:   txt1、txt2、txt3的Modify设为:Public
 private void btn1_Click(object sender, EventArgs e)
        {
            FrmS fs = new FrmS();
            fs.Owner = this;//Owner:拥有当前窗体的窗体
            fs.ShowDialog();
        }

FrmS:
 private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            FrmM fm = (FrmM)this.Owner;
            fm.txt1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            fm.txt2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            fm.txt3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
            this.Close();
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值