0
votes

Let's say I have two forms: Form1 and Form2. Form1 has a textbox, Textbox1 and Button1.

When Button1 is clicked, a new instance of Form2 is created and shown. If Form2 needs to access Textbox1, how should expose it? Should Form2 have a public variable to hold a reference to the textbox? Or, when Form2 closes, should it invoke some public method on Form1 that updates the textbox? Thanks for your advice.

2

2 Answers

2
votes

You should probably add a public property to the first form that exposes the textbox's text.

However, much more importantly, you should name your controls and forms.
There is (almost) nothing worse than a form with controls textBox1, button1, comboBox13, checkBox37.

1
votes

If Form2 needs the text box value from Form1 when it loads, I would add the value to Form2's constructor method and pass it in that way.

If Form1 needs to obtain a new value entered in Form2 you can create a delegate with an Event that passes the value back to an assigned event handler in Form1.

Creating a public property may be the fastest solution, but I would try to stay away from circular references between forms if that is the case.

Hope this helps!