views:

328

answers:

3

I have a sub folder that has an aspx page and a web.config file that overrides a connection string in the web.config in the root directory. The problem is if the aspx page contains any user controls the user controls still get the connection string from the web.config in the root directory. Is there anyway to force them to use the web.config that the parent aspx page uses?

+2  A: 

I suppose your user controls are at the root directory or in a directory that doesn't have a web.config, so they use the root web.config. Cause of the problem is this.

For solution, I think in your page you can set connection string to its user controls by a property. Or you can let your user controls to access connection string over page with a method.

Canavar
A: 

If it's just a connection string (or just a few setup variables) you could just pass them to your control from the parent page.

In your page containing the troublesome user control, you could reference the control in your aspx page and then on initialising your aspx page and its control, you could override the connection string in it's contructor/custom function

In your aspx page

<%Reference Src="path/to/your/control"%>

Code side (aspx)

// - check if this works first
ASP.class_name_of_control_ascx(override_connection_string); 

// Other wise - created place holder on page for control/find control on page
UserControl ctrl = new ASP.class_name_of_control_ascx();
PlaceHolderOnPage.Controls.Add(ctrl);
((ASP.class_name_of_control_ascx)ctrl).RunMethod(override_connection string);

And then control side, just set up your default constructor and an override constructor to accept your connection string from the parent aspx page.

In your control you would then just use this override connection string.

danrichardson
+1  A: 

I'm guessing that your user controls some where in the implementation of the user control reads directly from the web.config. That however binds information to the user control that does really have to do with the user control. (information being how to get the connection string, not the connection string it self). That binding violates the single resposibility principle and is (indirectly) what's causing your problem. Instead of reading the connection inside the user control. Expose the connection string as a property and have the page set it when instantiating the control.

To take it a step further into well behaved design. your user control should probably not even know of the connection string but should instead have a worker class or even better you might want to rewrite to have a control for display purposes, a worker for retriving data and a mechanism for binding the retrieved data to you control.

Rune FS