使用委托进行窗体间的传值

实现步骤:

 1.创建窗体Form1和Form2
 2.在窗体1中添加一个按钮(Button)和文本框(TextBox)控件,窗体2添加文本框
 3.窗体1的按钮中点击事件中,加入窗体2对象并打开
 4.添加一个方法(ChangeTxtBox)用于更改Form1的文本框
 5.声明一个带参数的委托(MyDelegate),委托变量(ChangeDel)
 6.按钮中加入委托用于Form2传给Form1的值

实现细节:

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 使用委托进行窗体间传值
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.ChangeDel = new MyDelegate(this.ChangeTxtBox);
            f2.Show();
        }
        private void ChangeTxtBox(string msg)
        {
            this.textBox1.Text = msg;//更改Form1的文本框
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

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 使用委托进行窗体间传值
{
    public partial class Form2 : Form
    {
        public MyDelegate  ChangeDel { get; set; }
        public Form2()
        {
            InitializeComponent();
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string txt = this.textBox1.Text;//获取当前文本框的值
            if (ChangeDel != null)
            {
                ChangeDel.Invoke(txt);
            }
        }
    }
}

创建的委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 使用委托进行窗体间传值
{
    public delegate void MyDelegate(string msg);
    
}

效果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值