常用方法有:
一、通过委托(子窗体传值给父窗体)
效果图:
Form1类中代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ShowText(string strV)
{
this.textBox1.Text = strV;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(ShowText);
form2.ShowDialog();
}
}
Form2类中代码:
public delegate void DelSendValue(string str);
public partial class Form2 : Form
{
//委托类型字段,存储Form1传送过来的函数
private DelSendValue delMethod;
//------
//public delegate void GetTextHandler(string text);
public Form2(DelSendValue del)
{
this.delMethod = del;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
//通过委托传值给窗体1,实际上运行的是窗体1的ShowText方法
private void button1_Click(object sender, EventArgs e)
{
if (delMethod != null)
{
this.delMethod(this.textBox1.Text.Trim());
}
}
}
二、【通过Form类构造方法的重载传参】父窗体传值给子窗体
Form1类中代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(textBox1.Text);
f2.ShowDialog();
}
}
Form2类中代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(string str)
{
InitializeComponent();
textBox1.Text = str; //
}
}
三、通过事件
form1代码
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();
//}
//private void Change_Text(string str)
//{
// textBox1.Text = str;
//}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ChangeText += (str) => textBox1.Text = str; //用lambda表达式实现
f2.ShowDialog();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
form2代码
//public delegate void ChangeTextHandler(string str); //定义委托
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//public event ChangeTextHandler ChangeText; //定义事件
public Action<string> ChangeText; //之前的定义委托和定义事件由这一句代替
private void button1_Click(object sender, EventArgs e)
{
if (ChangeText != null) //判断事件是否为空
{
ChangeText(textBox2.Text); //执行事件
this.Close();
}
}
}