Global Objects in User Controls

G

Guest

[note: I am relatively new to ASP.NET, so I'm very possibly doing something
stupid or overlooking something obvious. Please be forgiving, and walk me
through your answer as much as possible. Much appreciated.]

Here is the situation. I'm developing an application where:

I have defined a class (DBClass) to provide an abstraction layer for
interacting with a database. When an instance of the class is created, it
creates a connection to the database. My initial plan was that, at the very
top of each page I would:
1) include the DBClass class file, so the page knows about the class
2) create an instance of DBClass, which I call DB.
My thought was, once the DB instance was created, I would be able to use it
anywhere on the page.

However, on the page I am also making use of a "user control". This user
control has to have access to the database. When I simply reference DB in
the control file, the compiler complains, because I have not created the
instance DB in the control file.

I'm sure I'm probably just approaching this the wrong way or leaving out
something obvious.... can anyone help?

--G
 
M

Mark Fitzpatrick

You could create a property on the user control that can then be set in the
page. So in the code in the page you would have userControl.ReferenceDb =
DB;

You'll have to toy with where you can make use of this. For example, the
Page_Load events of the user control and the page are fired at different
times so typically if you want to use a property in a control that was set
by the page you would write the code in an overloaded onprerender event.
 

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

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top