Reputation: 13
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
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
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
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
Reputation: 1177
You can create a static class
with static properties
inside that. That will do it.
Upvotes: 0