Reputation: 67223
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?
Upvotes: 0
Views: 1735
Reputation: 235
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
or public static bool[] test = new bool[5];
In your other forms, you can just create an instance. DB db = new DB();
then grab the information using db.test = true/false
. This is what I've been doing and it works great.
Sorry, I'm only like a year late.
Upvotes: 0
Reputation: 9607
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.:
public string StoredText
{
get;
private set;
}
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:
public string GetSomeValue()
{
var form = new F2();
form.ShowDialog();
return form.StoredText;
}
Just ensure that StoredText
is populated (or not, if appropriate) before the form is closed.
Upvotes: 4
Reputation: 61599
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:
public string GetSomeValue()
{
var form = new F2();
form.ShowDialog();
return form.TextBox1.Text;
}
And called in code:
Label1.Text = GetSomeValue();
Upvotes: 3