C# - Winforms - Global Variables

C# - Winforms - Global Variables

yes you can by using static class.
like this:

static class Global
{
private static string _globalVar = "";

public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}

and for using any where you can write:

GlobalClass.GlobalVar = "any string value"

how to store in a global variable c#

If we are talking about a Windows Forms application, and by "global" you mean "common across the process," then you can use a static variable.

In this example i create a special class just to hold static variables, and declare one field and one property that will be available to your program and will hold one and only one value across the entire process.

static class GlobalVariables
{
static public string SomeVariable { get; set ; } //As a property
static public string SomeOtherVariable; //As a field
}

Note that if your program is multi-threaded, it may be a good idea to put a critical section around static variables, like this:

static class GlobalVariables
{
static private string LockObject = new Object();
static private string _someVariable;

static public string SomeVariable
{
get
{
lock(LockObject) { return _someVariable; }
}
set
{
lock(LockObject) { _someVariable = value; }
}
}
}

Global variable approach in C# Windows Forms application? (is public static class GlobalData the best)

As others have stated, you can use AppSettings to store simple data. The basics are easy; going beyond them is hard (see App.Config and Custom Configuration Sections). You can also serialize classes to XML or JSON, write custom storage formats, use databases, etc.

Making the configuration available throughout your application is a separate issue. Static classes and Singletons are inherently difficult to test, and introduce coupling throughout your other classes. One option is to create an interface for your configuration data class, create and load the configuration on startup, then pass the interface to any class that needs it (often as a constructor parameter). This is called Dependency Injection.

If you're doing this a lot, there are libraries that will make it easier (after you get past the learning curve). See List of .NET Dependency Injection Containers (IOC).

How do I keep track of a global variable in a Windows Forms MDI application?

You can store application-scope settings in the .settings file under Project->Properties->Settings. Please refer to MSDN for more information: https://msdn.microsoft.com/en-us/library/k4s6c3a0(v=vs.110).aspx.

You could also use your own custom static class to store and share settings between classes and forms:

public static class ApplicationService
{
public static string YourSetting { get; set; }
}

Sample Usage:

//set in Form1:
ApplicationService.YourSetting = "x";

//retrieve in Form2:
var setting = ApplicationService.YourSetting = "x";

Global variables in Visual C#

How about this

public static class Globals {
public static int GlobalInt { get; set; }
}

Just be aware this isn't thread safe. Access like Globals.GlobalInt

This is probably another discussion, but in general globals aren't really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

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

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

Windows Forms Application C#: adding global variables:

If you are using Command objects It's better to open and close connection yourself. If you are using DataAdapter, you can let the adapter control state of connection.

You should know Sharing a connection is not a good idea. ADO.Net will do it using connection pooling if required and I recommend you to open and close connections manually.

But based on your request here is the code you can use:

public class Form1:Form
{
public Form1()
{
InitiallizeComponent();
}

private OdbcConnection connection;

//If you want to open and close connection automatically uncomment commented codes
//Then you don't need to open and close connection manually
protected override void OnLoad(EventArgs e)
{
connection= new OdbcConnection("your connection string here");
//this.Connection.Open();
base.OnLoad();
}

protected override void OnClosing(CancelEventArgs e)
{
//this.Connection.Close();
this.Connection.Dispose();
base.OnClosing(e);
}
}

how create windows global variables in c# winform

basically you can accomplish by

  1. storing value in a storage accessible from different programs
  2. using some process to process comunication mechanism (IPC mentioned by @SLaks)

storages that comes to my mind could are: database, windows registry, settings file

process to process communication may be WCF, or System.IO.Pipes, or others: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365574(v=vs.85).aspx

it all depends on your needs. Is it performace critical? Do you need to infrom the other process that value has changed, or the other process will just request the value? How many processes will access the value at the same time?

How would I go About Getting a Global Variables value in another form?

You can acomplish this by passing the variable to the constructor of the second form.
Let's assume you want to send the IsManager value to the second form. Call the second form while passing the value to the constructor:

Form2 f2 = new Form2(IsManager);

In the second form, read the value:

public partial class Form2 : Form
{
private bool IsManager;
public Form2(bool isManager)
{
InitializeComponent();
IsManager = isManager;
}
//Render button or whatever based on IsManager value;
}

EDIT: To check if the button needs to be enabled or not:

public partial class Form2 : Form
{
private bool IsManager;
public Form2(bool isManager)
{
InitializeComponent();
IsManager = isManager;
setButtonVisibility(); //call method setVisibility() -> this is what was missing in your code

}
private void setButtonVisibility()
{
if(IsManager == true)
{
MessageBox.Show("Button Message Display");
//or YourButton.Enable = true; in order to enable it.
}
}
}

In your second form, there are a couple of issues:

  • Class name and constructor name are not the same;
  • The parameter for the Form2 constructor is missing;
  • isManager should be assigned the value of IsManager which should have been passed as a parameter to the constructor.

Global variables v Settings in C#

Static methods and other members aren't bad practice in their own right. It is just that people less familiar with OO concepts tend to litter their code with static methods, properties and fields everywhere, without realising what the consequences are.

Generally, for things like configuration settings, helper and utility classes, abstract factories, singletons etc., having static members is perfectly acceptable.



Related Topics



Leave a reply



Submit