tags:

views:

59

answers:

2

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?

+2  A: 

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();
Matthew Abbott
That works! Thanks.
dotnetdev
+3  A: 

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.

Beth
Totally agree, I should have known that, you should really provide properties to access the values instead of exposing UI fields.I've edited your answer and +1 for the property.
Matthew Abbott
just curious- why public over friend? I wouldn't think this property would need to be read outside the .sln
Beth
In my specific case, it wouldn't have to be. Anyway, this worked fine.
dotnetdev