winform下窗口之间委托传值

大致思路:form1中定义一个委托,然后创建form2对象,通过form2的构造函数传过去一个方法作为参数,而在form2中声明一个委托类型的变量作为参数的构造函数...

//form1中的代码

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

namespace 窗口值1
{
    public delegate void ChangFormValue(string s1);//定义一个带参数的委托,接收form2的textbox1.text值
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(Chang);
            f2.ShowDialog();
        }
        public void Chang(string s2)
        {
            textBox1.Text = s2;
        }
    }
}

form2中的代码:

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

namespace 窗口值1
{
    public partial class Form2 : Form
    {
       private ChangFormValue cv;
        public Form2()
        {
            InitializeComponent();
        }
        public Form2(ChangFormValue cvalue)
            :this()//cvalue==form1传过来的Chanag方法(方法作为参数)
        {
            this.cv = cvalue;//委托申明的变量指向传过来的方法
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            cv(textBox1.Text);//在上面cv指向chang方法后,就可以大胆的使用chang的方法了
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
       
    }
}

转载于:https://www.cnblogs.com/winchou/archive/2011/05/18/2050436.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值