窗体传参的方法
在上位机软件开发中经常会遇到需要在两个或多个窗体之间传递参数的问题。
比如,在参数输入时,弹出一个窗体输入要写入plc的数据,然后点击确认完成输入。
如下所示,在窗体Form1中,双击textbox控件,弹出窗体2,输入相应的数据并确认后,窗体1中的textbox控件显示窗体2中输入的数据。

实现这个功能的方法有很多种,可以归为以下7类:
构造函数,公开成员,Tag属性,页面所有者,静态类中的静态变量,委托,事件;
这7中方法中比较推荐的是:使用Tag属性方法、静态类中的静态变量,委托,事件;
其中委托和事件是最常用的。
这里使用了三种方法来实现。
第一种方法是委托;
第二种方法是事件;
第三种方法是标准事件:
具体代码如下:
Form2窗体代码如下:
using System; using System.Windows.Forms; namespace 窗体传值 { public partial class Form2 : Form { //第一种方案,使用委托 public Action<string> actSetText; //第二种方案,使用事件Event public event Action<string> eventSetText; //第三种方式,使用标准事件 public event EventHandler setTextEventHandler; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //第一种方式,使用委托 //if (actSetText!=null) //{ // actSetText(this.textBox1.Text.Trim()); //} //第二种方式,使用事件 //if (eventSetText!=null) //{ // eventSetText(this.textBox1.Text.Trim()); //} //第三种方式,使用标准事件 if (setTextEventHandler != null) { valueData valueData = new valueData(); valueData.textValue = this.textBox1.Text.Trim(); setTextEventHandler(this, valueData); } this.Close(); } } }
Form1窗体中的代码如下:
using System; using System.Windows.Forms; namespace 窗体传值 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.textBox1.DoubleClick += TextBox1_DoubleClick; } private void TextBox1_DoubleClick(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Show(); //form2.actSetText = SetText;//第一种方案使用委托 //form2.eventSetText += SetText;//第二种方式使用事件 form2.setTextEventHandler += Form2_setTextEventHandler;//第三种方式使用标准事件 } private void SetText(string obj) { this.textBox1.Text = obj; } private void Form2_setTextEventHandler(object sender, EventArgs e) { this.textBox1.Text = ((valueData)e).textValue; Console.WriteLine(((Form)sender).Name); } } }
其中,如果使用第三种方法标准事件 ,需要创建一个类并实现EventArgs 接口,代码如下:
using System; namespace 窗体传值 { public class valueData : EventArgs { public string textValue { get; set; } } }
浙公网安备 33010602011771号