Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a value from one form to another

Tags:

c#

winforms

I have two forms, and I need pass a value from form1.textbox1 to 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;
}

` and 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;
}

when I click "save" on form2 and open debug I see "ed = 3; en = 5", but when i click "open form2" on form1 and open debug, i see "Ed = null; En = null;" and shows a blank form without value in textboxes. help please.

like image 630
Konstantin Mokhov Avatar asked Dec 01 '22 02:12

Konstantin Mokhov


2 Answers

You create a new form, so old values will be lost. Default values are 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

You can use static vars, which would be the easiest solution to archive your goal, but there are other ways like constructors, containers, events etc.

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

public static string Ed1
{
    get { return Ed; }
    set { Ed = value; }
}

And in the other form

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

Please be advised that a static variable exists only once for a class. So if you have multiple instances and you change the static variable in one, the change also affects all other instances.

like image 128
BudBrot Avatar answered Dec 16 '22 01:12

BudBrot


You can create constuctor for form2 which accept 2 arguments and access these variables

Form2 frm2 = new Form2(textBox1.Text,textBox2.Text);
frm2.Show(); 

Constructor would look like

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

    }

There are many ways to pass data between forms such as

   1) Using constructor
   2) Using objects
   3) Using properties
   4) Using delegates

Check this link for details http://www.codeproject.com/Articles/14122/Passing-Data-Between-Forms

Hope It helps!

like image 39
Nitin Varpe Avatar answered Dec 16 '22 01:12

Nitin Varpe