Accessing the same data from multiple forms using C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am in need of some guidance on asscessing the same data from multiple
forms. I tried using a collection, but everytime that I try to access the
collection, I have to use the new word.
colStuff ns = new colStuff
When I try to access the items in the collection, they are not there (ie the
values from a different form).

Could somebody point me in the right direction to get this working?

Thanks,
Sam Berry
 
You have two decisions to make here, not just one.

First, how are all of the forms that need the common data going to get
at the common data?

Second, in what form is it most convenient to store the common data?

Worry about the first problem first. That is, don't worry about whether
to use a collection or a specialized class or whatever. First figure
out how all of your forms are going to get at the common data.

If there is only ever going to be one copy of your common data for any
given run of your program, then you have two choices for providing
universal accessibility: using a static property, or creating a
singleton class.

The static property is the simplest solution. You can put the static
property in any class, but usually you would put it in your main class,
the one that starts up your application. It would look something like
this:

public class MyApplication
{
private static colStuff myData = null;

public static int Main(string[] argv)
{
MyApplication.myData = new colStuff(...);
}

public static colStuff Data
{
get { return MyApplication.myData; }
}
}

Now you can just say MyApplication.Data from any form and you will get
the collection.

The singleton option is a bit more complicated, but has some advantages
to do with polymorphism. It looks something like this:

public class colStuff
{
private static colStuff singleton = null;

private colStuff(...)
{
}

public static colStuff Instance
{
get
{
if (colStuff.singleton == null)
{
colStuff.singleton = new colStuff(...);
}
return colStuff.singleton;
}
}
}

Now you can say colStuff.Instance from anywhere in any form, and if
there is not already a colStuff then it will make a new one and return
it. If one has already been created then it will return that.

Once you've decided which method you want to use, you can then store
your common data using any structure you like.
 
Back
Top