C# .net通过委托事件来传值
Form1中:
using System;
using System.Windows.Forms;
namespace WindowsForms跨窗体传值大全
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ChangeText += new ChangeTextHandler(Change_Text);//将事件和处理方法绑在一起,这句话必须放在f2.ShowDialog();前面
f2.ShowDialog();
}
public void Change_Text(string str)
{
textBox1.Text = str;
}
}
}
Form2中:
using System;
using System.Windows.Forms;
namespace WindowsForms跨窗体传值大全
{
public delegate void ChangeTextHandler(string str); //定义委托
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public event ChangeTextHandler ChangeText; //定义事件
private void button2_Click(object sender, EventArgs e)
{
if (ChangeText != null)//判断事件是否为空
{
ChangeText(textBox2.Text);//执行委托实例
this.Close();
}
}
}
}