Winform中子窗体传值给父窗体的实现方法

鉴于最近有同志提问Winform中如何进行窗体间的传值,特在此说明一下。如果是父窗体传值给子窗体,这个很简单,利用属性字段传值即可。那么子窗体如何传值给父窗体呢?其实也很简单,用委托就可以。下面看一个案例:现有一个父窗体(MainForm)和一个子窗体(ChildForm),点击子窗体的按钮,就可以将Textbox中的内容传给父窗体的Label控件,如下图所示:
在这里插入图片描述
这里就涉及到C#中事件的订阅和发布了。在这个例子中子窗体负责传值,那么子窗体就是事件的发布者,主窗体接收子窗体的值,那么主窗体就是事件的订阅者,简单来说就是主窗体(订阅者)会随着子窗体(发布者)的改变而改变。
子窗体代码如下:

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 WindowsFormsApplication1
{
    public partial class ChildForm : Form
    {
        /// <summary>
        /// 传值事件
        /// </summary>
        public event Action<string> ByValueEvent;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ChildForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 传值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (ByValueEvent != null)
            {
                ByValueEvent(textBox1.Text);
            }
        }
    }
}

主窗体代码如下:

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 WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 子窗体
        /// </summary>
        private ChildForm childForm;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 接收子窗体传来的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadForm_Click(object sender, EventArgs e)
        {
            if (childForm == null || childForm.IsDisposed)
            {
                childForm = new ChildForm();
                childForm.ByValueEvent += text => label1.Text = text;
                childForm.Show();
            }
        }
    }
}

发布了99 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HerryDong/article/details/103004234