将值从一种形式传递到另一种形式 [英] Passing a value from one form to another form

查看:36
本文介绍了将值从一种形式传递到另一种形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名为 form1form2 的表单:

I have two forms named form1 and form2:

  • form1 由一个 label 和一个 button 组成.
  • form2 由一个 textBox 和一个 button
  • 组成
  • form1 is made of a label and a button.
  • form2 is made of a textBox and a button

当我点击form1 按钮时,这将显示form2.一旦我点击 form2 中的按钮,textBox 中的任何输入都应该写回 form1.label.
我有下面的代码,但它不起作用.

When I click the form1 button, this will show up form2. Any inputs in textBox should be written back to form1.label once I hit the button in form2.
I have the code below but it doesn't work.

// Code from Form 1
public partial class Form1 : Form
{
    public void PassValue(string strValue)
    {
        label1.Text = strValue;
    }
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2();
        objForm2.Show();
    }

}

// Code From Form 2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 objForm1 = new Form1();
        objForm1.PassValue(textBox1.Text);
        this.Close();
    }
}

还有截图:

我怎么能意识到这一点?

How can I realize that?

推荐答案

您无法访问您创建 form2 的 form1.在 form2 button1_Click 中,您创建了 Form1 的新实例,这与初始实例不同.您可以像这样将 form1 实例传递给 form2 构造函数:

You don't access your form1, from which you created form2. In form2 button1_Click you create new instance of Form1, which is not the same as initial. You may pass your form1 instance to form2 constructor like that:

   // Code from Form 1
 public partial class Form1 : Form
{
    public void PassValue(string strValue)
    {
        label1.Text = strValue;
    }
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2(this);
        objForm2.Show();
    }

}

// Code From Form 2

public partial class Form2 : Form
{
    Form1 ownerForm = null;

    public Form2(Form1 ownerForm)
    {
        InitializeComponent();
        this.ownerForm = ownerForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {       
        this.ownerForm.PassValue(textBox1.Text);
        this.Close();
    }
}

这篇关于将值从一种形式传递到另一种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆