how to share a Variable between 2 form? global var

2020-02-15 04:14发布

hi i want to share a variable between 2 form. 2 forms is in the one project. In fact,i want a global variable in the project how can i do it?

Language: c# .net

Thanks

标签: c# .net
4条回答
淡お忘
2楼-- · 2020-02-15 04:26

You can create a static class with static properties inside that. That will do it.

查看更多
够拽才男人
3楼-- · 2020-02-15 04:27

Create a public static property/method/variable.

查看更多
闹够了就滚
4楼-- · 2020-02-15 04:34

Create a static class with static field/property like following:

public static class DataContainer
{
    public static Int32 ValueToShare;
}

use it in multiple forms like following:

    public void Form1_Method()
    {
        DataContainer.ValueToShare = 10;
    }

    public void Form2_Method()
    {
        MessageBox.Show(DataContainer.ValueToShare.ToString());
    }
查看更多
爷、活的狠高调
5楼-- · 2020-02-15 04:38

The most straight forward way is to pass the variable to the forms.

It's hard to get into too much detail without knowing what your program does and how the forms are loaded, but I'd have the forms accept an argument in the constructor or something. If the argument is a reference type, both forms would reference the same data.

查看更多
登录 后发表回答