C#窗体间传递参数

C#窗体间传递参数

在编程中,经常遇到窗体间传值问题

这包括Form1向Form2传值,或Form2向Form1传值。

Form1–>Form2传递参数,如图:

image-20201017111319633

方法一:重载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传值,如图:

image-20201017112253033

通过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);
}
  • 3
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值