从一种形式传递一个值为另一种形式

从一种形式传递一个值为另一种形式

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

问题描述

我有一个名为两种形式 Form1中窗口2

I have two forms named form1 and form2:

  • Form1中是由标签按钮
  • 窗口2 是由的textBox 按钮
  • form1 is made of a label and a button.
  • form2 is made of a textBox and a button

当我点击 Form1中按钮,这将显示窗口2 。任何投入的textBox 应写回 form1.label 有一次我打了按钮窗口2
我有以下的code,但它不能正常工作。

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();
    }
}

和截图:

我怎么能知道呢?

推荐答案

您没有访问您的Form1中,从创建窗体2。在窗口2的button1_Click创建Form1中,这是不一样的初始的新实例。你可以通过你的Form1的实例窗口2构造这样的:

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();
    }![Application Screen Shot][1]

}

// 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();
    }
}

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

08-14 05:01