Where to keep global variables in Windows Forms App

  softwareengineering

I have here a Vb.Net employee management application.
It has employees, managers, teams, trainings and so on.

The way the application is set up now, data is read from the database in the startup form (frmMain) load event and kept in that forms public properties. After that all other forms (and there is many of them) reference those lists (list (of employee), list of (team)) usging those properties. For example

dim emp = frmMain.Employees.Find(Function(x) x.ID = 128) , or
dim team1 as new Team
frmMain.Teams.Add(team1)

I feel that this is a very bad way to solve this problem, but I’m stuck on deciding how this should be done.

Some singleton class that would keep all those lists (there is lots of them) instantiated on application startup, or is there a better way to do this?

1

I have solved this in the past by creating a public module called Globals.vb that contains one or more VB Structure types that logically group variables together. You can then create a single public instance of each structure. For example, an ApplicationState structure variable could have collection-oriented properties for your employees and teams. This lets you write code like this:

if ApplicationState.Teams.Contains(thisTeam) then ...

Or, from your example:

Dim emp = ApplicationState.Employees.Where(function(z) z.ID = 128).FirstOrDefault

This puts all global variables into a single, (relatively) easy to understand place and format. It also lets you use the Structure’s constructor to initialize your values.

3

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT