一、编码思路
在父窗体使用Lambda表达式自定义事件赋给子窗体内定义的事件,通过在子窗体内调用事件实现传参
二、传递的参数
创建文件SomeUtility.cs,在类SomeUtility中声明结构ReturnStruct
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EventTest{ public class SomeUtility { public struct ReturnStruct { public string sData1; public string sData2; public string sData3; public ReturnStruct(string s1, string s2, string s3) { sData1 = s1; sData2 = s2; sData3 = s3; } } }}
三、子窗体相关
窗体FormTip,里面有三个TextBox,单击确定会将三个TextBox的值传递到父窗体中
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 EventTest{ public partial class FormTip : Form { public class TEventArgs: EventArgs { public T Args { get; private set; } public TEventArgs(T args) { this.Args = args; } } [Browsable(false)] internal event EventHandler > EventTest; SomeUtility.ReturnStruct rs; public SomeUtility.ReturnStruct GetReturnStruct() { return rs; } //构造函数1:无参数 public FormTip() { InitializeComponent(); } //构造函数2:有一个ReturnStruct类型参数 public FormTip(SomeUtility.ReturnStruct r) { InitializeComponent(); this.rs.sData1 = r.sData1; this.rs.sData2 = r.sData2; this.rs.sData3 = r.sData3; } private void FormTip_Load(object sender, EventArgs e) { this.txtData1.Text = rs.sData1; this.txtData2.Text = rs.sData2; this.txtData3.Text = rs.sData3; } //单击“确定”按钮:调用事件EventTest private void btnOK_Click(object sender, EventArgs e) { //调用事件EventTest if (this.EventTest != null) { SomeUtility.ReturnStruct rs = new SomeUtility.ReturnStruct( this.txtData1.Text, this.txtData2.Text, this.txtData3.Text); this.EventTest(this, new TEventArgs (rs)); } //退出窗口 this.Close(); } //单击“取消”按钮:直接退出 private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } }}
四、父窗体相关
窗体FormMain,单击按钮btnTest打开子窗体,并在单击子窗体的“确定”按钮后根据子窗体内设置的值更新txtResult中的文本内容
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 EventTest{ public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void FormMain_Load(object sender, EventArgs e) { this.txtResult.Text = "1:- 2:- 3:-"; } private void btnTest_Click(object sender, EventArgs e) { SomeUtility.ReturnStruct rsTest = new SomeUtility.ReturnStruct("Data1", "Data2", "Data3"); FormTip frmTip = new FormTip(rsTest); frmTip.EventTest += (obj, args) => { SomeUtility.ReturnStruct rsTemp = frmTip.GetReturnStruct(); rsTest.sData1 = args.Args.sData1; rsTest.sData2 = args.Args.sData2; rsTest.sData3 = args.Args.sData3; this.txtResult.Text = string.Format("1:{0} 2:{1} 3:{2}", rsTest.sData1, rsTest.sData2, rsTest.sData3); MessageBox.Show("赋值成功"); }; frmTip.ShowDialog(); } }}
五、运行示例
1)打开父窗体FormMain
2)打开子窗体FormTip,输入三个值
3)将三个值传回父窗体FormMain
END