, , , , ,

Starting out with a basic Windows Form application, with variables declared in a public class called ‘OurColours’, the private class for each button is something like:

private void cmdRed_Click(object sender, EventArgs e)
txtSelected.Text = OurColours.red;

When the button is clicked the string in OurClass is displayed in the text box (txtSelected). But variables don’t need to exist in the same source file. They can exist in a shared object, as demonstrated in my previous post. Just as before, I’ve added a new Class Library project to the solution.


The new Class Library uses the GlobalParameters namespace, and the public class (userDefined) is copied into it:


Returning to the first project where the form was created, we add the GlobalParameters namespace to its references.


Now the code in each form button can be modified to point to variables in GlobalParameters.userDefined. e.g.

private void button4_Click(object sender, EventArgs e)
txtSelected.Text = GlobalParameters.userDefined.orange;

Writing to the Shared Object
A shared object also enables communication between forms. Within GlobalParameters.userDefined I added another variable called ‘lastSelected‘:
public static string lastSelected;

Then I added another line to each form button code, so it became like:
private void cmdBlue_Click(object sender, EventArgs e)
txtSelected.Text = GlobalParameters.userDefined.blue;
GlobalParameters.userDefined.lastSelected = txtSelected.Text + " was selected";

Finally I added another form that displays whatever string was passed to GlobalParameters.userDefined.lastSelected. This form has just one label (lblLastSelected), and the text is determined by adding the following after the InitializeComponent() line:
lblLastSelected.Text = GlobalParameters.userDefined.lastSelected;

And here is the finished article:


As a final note, we can add another class in the shared library, if ever the variables need to be grouped. To do this, simply add a new public class. The variables here are then referred to using GlobalParameters.newVariableGroup.[variable name].


Also, we might want to make the application portable, distributing it with the shared C# class as a Dynamic Link Library (DLL). This can be done by right-clicking the GlobalParameters References entry for the project, and setting its Copy Local property to ‘True’.


Download Visual Studio project…