C# WinForms Objects

J

Jon

Hello all,

I have a WinForms app that has a number of forms. When I login, I
create 3 objects, lets call them A, B & C.When I create them, I
connect to a database, return a load of data and set the members.

I need to 'Save' these objects somewhere as I need to reference their
members in number of the above mentioned forms, but I don't want to
create them again, as it's another hit on the database.

In ASP.NET, I'd keep them on a session, how would I do this in
WinForms?

Thanks,

JY
 
J

Jon

Any variety of ways.  For example...

If the objects are most closely associated with one of your forms, then
you could have that form actually retain the references and provide some
way for other forms with a reference to that form to get the objects
(e.g. via properties).

Alternatively, you could create a container object that holds the
references to the objects you want to keep, and then pass a reference to
that container object to each form when they are created.

Alternatively, you could create a cache of some sort, either in the form
of a singleton or a static class, in which the objects are stored.  Then
any code needing those objects would access them directly from the
singleton or static class.

This is far from an exhaustive enumeration.

With such a vague question, it's hard to offer anything more specific
than that.

Pete

That did the trick. I found a pattern for a Thread Safe Singleton.
Cheers Pete
 
R

Registered User

Hello all,

I have a WinForms app that has a number of forms. When I login, I
create 3 objects, lets call them A, B & C.When I create them, I
connect to a database, return a load of data and set the members.

I need to 'Save' these objects somewhere as I need to reference their
members in number of the above mentioned forms, but I don't want to
create them again, as it's another hit on the database.

In ASP.NET, I'd keep them on a session, how would I do this in
WinForms?

First thing I would do is create a container type for the data that is
to be shared between Form1 and Form2. Name the type MyData for this
example.

In the file Form1.cs, underneath the Form1 class add a public class,
MyForm, which derives from Form. To this class add a public property
of type MyData named SharedData.

Next change Form1.cs and Form2.cs so that both are derived from type
MyForm instead of Form. To create an instance of Form2 from an
instance of Form1

Form2 form = new Form2();
// this pointer is Form1 instance
form.SharedData = this.SharedData;
form.ShowDialog();

Obviously the SharedData property will need to be initialized at some
point.

regards
A.G.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top