I have a winforms application.
I have a textbox on one form (call F1) and when a button is clicked on this form (call F2), it launches another form.
On F2, I want to set a string via a textbox (and save it to a variable in the class), and then when I close this form, the string will appear in a label in F1.
So I am basically sharing variables between both forms. However, I can't get this to work correctly. How would this code look?
This might not be the most efficient way of approaching, but you could create a class called DB (database). Inside this class, create variables like
public static bool test
orpublic static bool[] test = new bool[5];
In your other forms, you can just create an instance.
DB db = new DB();
then grab the information usingdb.test = true/false
. This is what I've been doing and it works great.Sorry, I'm only like a year late.
Are you showing the second form as a dialog, this is probably the best way to do it. If you can avoid doing shared variables, you could do the following:
And called in code:
I would add a new property to form2. Say it's for a phone number. Then I'd add a friend property m_phone() as string to form 2. After showing an instance of form2 but before closing it, you can refer to the property m_phone in form1's code.
It's an additional level of indirection from Matthew Abbott's solution. It doesn't expose form2 UI controls to form1.
EDIT
e.g.:
inside the set you can refer to your UI control, like return textBox1.text. Use the get to set the textbox value from an earlier load.
And:
Just ensure that
StoredText
is populated (or not, if appropriate) before the form is closed.