C#窗体间传递参数
在编程中,经常遇到窗体间传值问题
这包括Form1向Form2传值,或Form2向Form1传值。
Form1–>Form2传递参数,如图:
方法一:重载Form2的构造函数
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(textBox1.Text);
frm.Show();
}
Form2窗口:
public Form2(string pars)
{
InitializeComponent();
test = pars;
}
string test;
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = test;
}
方法二:通过公共变量传值,但变量需要声明为静态 变量:public static
Form1窗口:
public static string test;
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
}
Form2窗口:
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = Form1.test;
}
方法三:通过在Form2中声明公共变量,可以避免变量被窗体实例化
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.test = textBox1.Text;
frm.Show();
}
Form2窗口:
public string test;
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = test;
}
Form2–>Form1传值,如图:
通过Form2向Form1传值,均需要将Form1设置为Form2的所有者
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 child = new Form2();
child.Show(this);
}
Form2窗口:
private void button1_Click(object sender, EventArgs e)
{
Form1 parent = (Form1)this.Owner;
parent.SetValue = txtChild.Text;
}
//方法一 将form1设置为form2的拥有者,在form2中访问form1的控件
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 child = new Form2();
child.Show(this);
}
Form2窗口:
private void button1_Click(object sender, EventArgs e)
{
Form1 parent = (Form1)this.Owner;
parent.Controls["txtParent"].Text = txtChild.Text;
}
//方法二 在Form1中赋值属性
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 child = new Form2();
child.Show(this);
}
public string SetValue
{
set { txtParent.Text = value; }
get { return txtParent.Text; }
}
Form2窗口:
private void button1_Click(object sender, EventArgs e)
{
Form1 parent = (Form1)this.Owner;
parent.SetValue = txtChild.Text;
}
//方法三 在Form1中创建一个赋值参数的方法
Form1窗口:
private void button1_Click(object sender, EventArgs e)
{
Form2 child = new Form2();
child.Show(this);
}
public void SetValue(string text)
{
txtParent.Text = text;
}
Form2窗口:
private void button1_Click(object sender, EventArgs e)
{
Form1 parent = (Form1)this.Owner;
parent.SetValue(txtChild.Text);
}