将值从一种形式传递给另一种形式

Kon*_*hov 4 c# winforms

我有两种形式,我需要从form1.textbox1传递一个值到form2.variable

Form1中:

string Ed = "", En = ""; 

public string En1
{
    get { return En; }
    set { En = value; }
}

public string Ed1
{
    get { return Ed; }
    set { Ed = value; }
}
private void button1_Click(object sender, EventArgs e)
{

    Form2 F2 = new Form2();
    F2.Show();
    F2.textbox1value = Ed;
    F2.textbox2value = En;
}
Run Code Online (Sandbox Code Playgroud)

`和Form2:

public string textbox1value
{
    get { return textBox1.Text; }
    set { textBox1.Text = value; }
}
public string textbox2value
{
    get { return textBox2.Text; }
    set { textBox2.Text = value; }
}

private void button1_Click(object sender, EventArgs e)
{
    Form1 F1 = new Form1();
    F1.Ed1 = textBox1.Text;
    F1.En1 = textBox2.Text;
}
Run Code Online (Sandbox Code Playgroud)

当我在form2上单击"保存"并打开调试时,我看到"ed = 3; en = 5",但是当我在form1上单击"打开form2"并打开调试时,我看到"Ed = null; En = null;" 并在文本框中显示没有值的空白表单.请帮忙.

Bud*_*rot 12

您创建一个表单,因此旧值将丢失.默认值为null.

Form1 F1 = new Form1(); //I'm a new Form, I don't know anything about an old form, even if we are the same type
Run Code Online (Sandbox Code Playgroud)

您可以使用静态变量,这是归档目标的最简单的解决方案,但还有其他方法,如构造函数,容器,事件等.

public static string En1
{
    get { return En; }
    set { En = value; }
}

public static string Ed1
{
    get { return Ed; }
    set { Ed = value; }
}
Run Code Online (Sandbox Code Playgroud)

而在另一种形式

private void button1_Click(object sender, EventArgs e)
{
    Form1 F1 = new Form1();
    Form1.Ed1 = textBox1.Text;
    Form1.En1 = textBox2.Text;
}
Run Code Online (Sandbox Code Playgroud)

请注意,类的静态变量只存在一次.因此,如果您有多个实例并且您将静态变量更改为一个,则更改也会影响所有其他实例.


Nit*_*rpe 8

您可以创建form2接受2个参数的constuctor 并访问这些变量

Form2 frm2 = new Form2(textBox1.Text,textBox2.Text);
frm2.Show(); 
Run Code Online (Sandbox Code Playgroud)

构造函数看起来像

public Form2(string txt1,string txt2)
    {
        InitializeComponent();
        textbox1value.Text = txt1;
        textbox1value.Text=txt2

    }
Run Code Online (Sandbox Code Playgroud)

有很多方法可以在表单之间传递数据

   1) Using constructor
   2) Using objects
   3) Using properties
   4) Using delegates
Run Code Online (Sandbox Code Playgroud)

有关详细信息,查看此链接 http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms

希望能帮助到你!