且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在2种形式之间共享变量?项目中的全局变量

更新时间:2023-11-14 08:38:58

使用静态字段/属性创建静态类,如下所示:

 公共静态类DataContainer 
{
public static Int32 ValueToShare;
}

以多种形式使用它,如下所示:

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

public void Form2_Method()
{
MessageBox.Show(DataContainer.ValueToShare.ToString());
}


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

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());
    }