Reputation: 861
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
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
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
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