winform 利用委托实现窗体传值

本文介绍了一种使用委托和事件实现C#窗体间数据传递的方法。具体步骤包括在子窗体Form2中定义委托及事件,在Form1中通过事件处理函数获取数据并更新Form2中的显示。

       父窗体:Form1    ,有个 textbox1.text ,有个button1

  子窗体:Form2  ,有个 textbox1.text ,有个button1

  修改Form1 的textbox1.text  ,点击Form1的 button1,弹出Form2,点击Form2 的button ,结果:Form2的 textbox1.text 的值为  Form1的textbox1.text ,修改下 Form1的textbox1.text ,再点Form2 的button  ,Form2的 textbox1.text 的值与Form1的 textbox1.text 保持一致

 

首先在Form2中定义委托和事件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestDelegate
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        public delegate string TransfDelegate();   //委托的方法体必须返回值为string,无参数

        public event TransfDelegate TransfEvent;

        private void button1_Click(object sender, EventArgs e)
        {         
            textBox1.Text = TransfEvent();
        }    

       
      
    }
}

  

  

然后在Form1中进行调用:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestDelegate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
       
        private void button1_Click(object sender, EventArgs e)
        {            
            Form2 frm = new Form2();
            //注册事件
            frm.TransfEvent += GetValueEvent;
            frm.Show();
        }

        string GetValueEvent()   
        {
            return textBox1.Text;
        }
    }
}

  

  

转载于:https://www.cnblogs.com/wdw31210/p/7592112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值