0
votes

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.

3
The eternal Winforms question. Add form1.Show(); You can't learn object-oriented programming with trial and error. Use a book or a class to learn the basics. - Hans Passant
@HansPassant Assuming he said But the value "Test Name" does not appear in form1's textbox, I figured the form did show up. Otherwise, you are probably right. - Dion V.
@Nomistake Then you should not create a new one! - Dion V.
@DionV. Ok, i did this to access the textbox in form1, but i guess this isnt the rigth approach... Thank you - Nomistake
@HansPassant "You can't learn object-oriented programming with trial and error. Use a book or a class to learn the basics" Waaaauw! - Nomistake

3 Answers

3
votes

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.

0
votes

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);

-1
votes

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?