1通过Form类构造方法的重载传参:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(textBox1.Text);
f2.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(string str)
{
InitializeComponent();
textBox2.Text = str;//这句必须放在InitializeComponent();的后面,否则会引起“空引用异常”
}
}
2通过外部可访问的中间变量传参:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.str = textBox1.Text;
f2.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string str;//这里str是在Form2类中定义的,并且不需要static关键字
private void Form2_Load(object sender, EventArgs e)
{
textBox2.Text = str;
}
}
3子窗体向父窗体传值的方法 使用公共静态变量传值
主窗体frmMain中代码
public partial class frmMain : Form
{
//声明工位ID 为公共静态变量
public static string terminalID = "";
//给静态变量赋值
terminalID = "q13bh01-bh12";
}
子窗体frmGroup中代码
private void frmGroup_Load(object sender, EventArgs e)
{
this.txtTerminalID.Text= frmMain.terminalID.Trim();
//可以再赋值给静态成员,方便其他窗体调用
frmMain.terminalID = "q13bh01-bh11";
}