winform实现窗口传值
在WinForms应用程序中,实现窗体间传值可以通过几种方式:
方式一通过构造函数传值
第一个窗体
public partial class Form1 : Form{public Form1(){InitializeComponent();}private void buttonOpenForm2_Click(object sender, EventArgs e){using (Form2 form2 = new Form2(textBoxValue.Text)){if (form2.ShowDialog() == DialogResult.OK){// 接收Form2传回的值string valueFromForm2 = form2.ReceivedValue;// 处理接收到的值}}}}
第二个窗体
public partial class Form2 : Form{public string ReceivedValue { get; private set; }public Form2(string value){InitializeComponent();ReceivedValue = value;// 设置Form2中的控件,使用传递过来的值}private void buttonSendValueBack_Click(object sender, EventArgs e){// 处理传回的值逻辑ReceivedValue = textBoxSendValue.Text;// 设置DialogResult以通知Form1传值完成this.DialogResult = DialogResult.OK;}}
方式二 定义事件委托然后在父窗体中给事件赋值
form1
public partial class Form1 : Form{public Form1(){InitializeComponent();}// 方式二 定义事件委托然后在父窗体中给事件赋值private void button2_Click(object sender, EventArgs e){Form3 f3 = new Form3();f3.h2 += F3_h1;f3.ShowDialog();}private void F3_h1(string obj){this.textBox1.Text = obj;}}
form2
public partial class Form2 : Form{//定义事件public event Action<string> h1;public delegate void DEL(string s);public DEL h2;public Form2(){InitializeComponent();}private void textBox1_TextChanged(object sender, EventArgs e){h2(textBox1.Text);}}
提示
在winform中可以通过设置控件的Modifiers属性来设置控件的可访问性