使用委托进行窗体传值

两个窗口,第一个窗口中有按钮和label,点击按钮用来打开窗口2;

在窗口2中有textbox和按钮,点击按钮,将textbox中的值传递给窗口1,并在窗口1的label上显示。

分析:在窗口1有label显示的方法,但是在窗口2中有需要显示的值。这时需要使用委托,将窗体1的显示方法传递到窗体2中。传递方法可通过委托作为Form2构造函数的形参

Form1.cs

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 fm2 = new Form2(showMsg);
            fm2.Show();
        }

        //需要将这个方法传递到窗体2中
        void showMsg(string str)
        {
            label1.Text = str;
        }
    }
}

From2.cs

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 窗体传值
{
    //声明委托,用于窗体传值
    //与void showMsg(string str)的标签一致
    public delegate void DeleSend(string str);
    public partial class Form2 : Form
    {
        //用来接收收到的函数
        public DeleSend _dele;
        public Form2(DeleSend dele)
        {
            //这样将Form1的方法传递到了Form2中
            //Form2可以调用From1的方法
            this._dele = dele;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //在Form2中调用Form1的方法
            _dele(textBox1.Text);
        }
    }
}
原文地址:https://www.cnblogs.com/my-cat/p/7831296.html