Winform利用委托实现子窗体传值给父窗体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32832727/article/details/54292989

首先,新建两个窗体,父窗体Form1和子窗体Form2,添加控件如下。实现在子窗体的textBox中输入字符,实时显示在父窗体的textBox中的功能。


子窗体中代码:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    //声明一个委托,该委托有个string类型的参数。委托不一定要声明在这里,也可声明在其他命名空间中
    public delegate void Mydel(string str);
    public partial class Form2 : Form
    {
        //定义一个委托对象
        public Mydel del;
        public Form2()
        {
            InitializeComponent();
        }
        //在textBox控件的事件中,找到TextChanged事件
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            //调用委托对象,参数是子窗体的textBox中的内容
            del(textBox2.Text);
        }
    }
}
父窗体中代码:
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            //在子窗体show之前,将方法赋给子窗体中的委托对象
            f2.del = textshow;
            f2.ShowDialog();
        }
        //一个方法,将内容显示在父窗体的textBox中
        void textshow(string str)
        {
            textBox1.Text = str;
        }
    }
}
效果:




猜你喜欢

转载自blog.csdn.net/sinat_32832727/article/details/54292989