user538811
user538811

Reputation: 13

how to share a Variable between 2 form? global variable in the project

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

Upvotes: 1

Views: 26201

Answers (5)

Robert Bolton
Robert Bolton

Reputation: 673

To pass data in (and get data out), I created a custom UserControl and placed it on the main form. This allowed me to then look-up the UserControl from other forms and manipulate the properties on it.

Upvotes: 0

decyclone
decyclone

Reputation: 30830

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

Upvotes: 7

Jonathan Wood
Jonathan Wood

Reputation: 67223

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.

Upvotes: 0

Hps
Hps

Reputation: 1177

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

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166406

Create a public static property/method/variable.

Upvotes: 0

Related Questions