-2

in windows application I have 2 forms: form1 containing a TextBox. I just want to use the value of the form1's textbox in form2, so in form2 I just create a object of form1 and try to access the value of textbox by writing the code:

form1 f1=new form1();
string value=f1.textbox1.text

...but the value is not coming.....please help me

Markus
  • 20,838
  • 4
  • 31
  • 55
user3056671
  • 47
  • 2
  • 3

1 Answers1

0

Creating a new instance of Form1 will not work as it a new instance, not the one you were using. As the comments above suggest, the best option would be to create a custom constructor for Form2 and accept the textbox value there.

public Form2(string form1TextBoxValue)
{
    this.ValueFromForm1 = form1TextBoxValue;
}

Therefore in Form1 you can use the value in Form2 when you instantiate it:

Form2 form2 = new Form2(this.textBox.Text);

Alternatively, you could pass the Form1 instance to Form2. This way you can access all the Form1 values if needed. This does mean that Form2 has a direct dependence on Form1 which should be avoided.

// In Form2
public Form2(Form form1Instance)
{
    this.Form1Instance = (Form1)form1Instance;
}

// In Form1
Form2 form2 = new Form2(this);
BWHazel
  • 1,474
  • 2
  • 18
  • 31