Nomistake
Nomistake

Reputation: 861

Getting Form2 variable to Form1 (User text input in TextBox)

The plan: I want to ask the user with second Form2 to input some text. When this Form2 is closed, i want to display the input text in a textbox on Form1...

On a button event, on Form2 i can reach Form1's textbox:

Form1 form1 = new Form1();

And:

form1.myText = "Test Name";

And then i close Form2:

this.Close();

But the value "Test Name" does not appear in form1's textbox... I don't get an error.

Upvotes: 0

Views: 216

Answers (3)

Łukasz Rejman
Łukasz Rejman

Reputation: 1892

When you call new Form1(), then new instance of Form1 is created. You have two objects of Form1. That's why your code doesn't work.

If you want to make it fast, add Form1 as a variable to Form2 class.

public Form1 form1;

Then you can set it just before showing Form2.

Form2 form2 = new Form2();
form2.form1 = this;
form2.Show();

Remember to remove this part: Form1 form1 = new Form1();.

Now your code should work.

Upvotes: 3

puko
puko

Reputation: 2980

Create event handler on Form2 and when open Form2 from Form1 hook on this event. In form2 fire this event with your own eventargs which contains text which u need to show in Form1.

Another solution is Action. Create property Action in Form2 and when opened Form2 set this action. When Form2 is closed fire this action like _action.Invoke(textWhichUneed);

Upvotes: 0

Yuriy Zaletskyy
Yuriy Zaletskyy

Reputation: 5151

You should make assign value before close. For example

form1.myText = "Test Name";
this.Close();

Also form1 shouldn't be created, but passed. How do you pass form1 into form2?

Upvotes: -1

Related Questions