Link to home
Start Free TrialLog in
Avatar of GaryHoff
GaryHoff

asked on

setting asp:SqlDataSource ConnectionString from Application object

I want to set my asp:SqlDataSource ConnectionString from Application["connstring"] instead of using web config.
I'm trying:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%=Application["ConnString"]%>'
which doesn't work.

This works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnString %>"
but it reads from web.config.

I need to have it read from the application object.
Anyone know the correct systax to do that?

Avatar of Gary Davis
Gary Davis
Flag of United States of America image

Call a public method that returns the string Application["connString"]. This would allow you to verify the string is actually there (non-null) and handle the error case (provide a default or redirect to error page and/or log the error.

Gary Davis
Avatar of GaryHoff
GaryHoff

ASKER

What is the correct symtax?

ConnectionString="<%=getConnString()%>"
doesn't work, get run time error message "Keyword not supported: '<%'.".
ASKER CERTIFIED SOLUTION
Avatar of Gary Davis
Gary Davis
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Add a typecast for string and that worked.  Thanks.
SqlDataSource1.ConnectionString = (string)Application["connString"];

Note for others looking at this.  Put the above line BEFORE any test for "Page.IsPostBack". It must be reset for every call, expecially if you are using AJAX.
Here's a tip. This is what we do on our web. We keep our connection strings in an XML file. When a page needs to get the connection string, it calls a routine we have that loads the connection string from Cache. If it is not in cache, it reads the XML file to get the string and then saves it in Cache.

If we need to switch our databases like to our DR site, we have a web page that lets the DBAs modify the XML file to point the connection string to the other database server. The Cache object has the file as a dependency so saving the file purges it from Cache forcing it to be reloaded and immediatly, the web pages are now on the new server.

Gary Davis
Thanks.