0

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?

Timwi
  • 65,159
  • 33
  • 165
  • 230
GurdeepS
  • 65,107
  • 109
  • 251
  • 387

3 Answers3

4

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
  • 9,531
  • 1
  • 24
  • 43
  • 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 Aug 24 '10 at 06:39
  • just curious- why public over friend? I wouldn't think this property would need to be read outside the .sln – Beth Aug 24 '10 at 12:59
  • In my specific case, it wouldn't have to be. Anyway, this worked fine. – GurdeepS Aug 25 '10 at 22:53
3

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
  • 60,571
  • 9
  • 104
  • 129
0

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.

Brandon
  • 68,708
  • 30
  • 194
  • 223
NothinRandom
  • 225
  • 1
  • 4
  • 12