Sharing a variable between two winforms

2020-05-07 04:36发布

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?

标签: c# winforms
3条回答
够拽才男人
2楼-- · 2020-05-07 05:14

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.

查看更多
forever°为你锁心
3楼-- · 2020-05-07 05:15

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();
查看更多
SAY GOODBYE
4楼-- · 2020-05-07 05:37

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.

查看更多
登录 后发表回答