Sunday, April 28, 2019

Passing Data Using Static Classes

Typically, when I see questions on the Forums about passing data between Forms, the questions are usually about passing data in, what I will call, the "classic" sense: two Forms are open, one is used for gathering data and the other is used for manipulating and/or displaying data. For those types of questions, I refer the person to my blog posts from many years ago:

http://geek-goddess-bonnie.blogspot.com/2011/01/passing-data-between-forms.html
http://geek-goddess-bonnie.blogspot.com/2012/12/passing-data-between-forms-redux_31.html

And this one is often relevant too:

https://geek-goddess-bonnie.blogspot.com/2010/06/program-to-interface.html

I came across a question yesterday that at first seemed like it was going to be about passing data in the "classic" sense. Until I thought some more about what the person was actually asking about:  the "data-gathering" Form was a Login Form and it would collect information from the user, an Account Number for example. They then wanted to display that information on all other Forms in the application.  Since Login Forms are displayed at application start-up and then they "go away", we no longer have the ability to pass the data in the "classic" sense (two Forms are not going to both be open). Some other mechanism is needed.

This particular scenario with a Login Form, in my opinion, only requires a static class with static properties. For this application, I think that a singleton class would be overkill (because the class is only ever going to be populated at application startup and nowhere else or at any other time).

So, let's start with a static Account class:

public static class AccountClass
{
public static string AccountNumber { get; set; }
// plus, any other static info you'd like to share with your other Forms
}

In your LoginForm, perhaps after the user had clicked OK to login, you'd want to set the static members of the AccountClass:


private void OKButton_Click(object sender, EventArgs e)
{
AccountClass.AccountNumber = this.txtAccountNumber.Text;
// plus, whatever else you need to do in this button click
}

Then, in any other Forms where you need this information, get it from the static class. For example, to display the AccountNumber in a label on your Form, take care of that in the Form's constructor:

public CustomerForm()
{
InitializeComponent();
this.lblAccountNumber.Text = AccountClass.AccountNumber;
}

Happy Coding! =0)