Wednesday, August 11, 2010

How to set dynamic connection string to SQLDataSource

There are some occations where we cant have fixed connection string in the web.config but we have to utilize username and password from the current context to login to database server. So such a case having SqlDataSource declared declaratively in <%$ ... %>,  best option to attach an on-init event handler to SqlDataSource.
  <add name="LocalTestSqlServer" 
        connectionString="Data Source=CHARITH; Initial Catalog=Test; User ID={0}; Password={1}"/>

Consuming Page:
<%@ Page Language="C#" %>
<html xmlns="">
<head id="Head1" runat="server">
 <script runat="server">
        protected void SetCredentials(object sender, EventArgs e)
            SqlDataSource sdt = sender as SqlDataSource;
            sdt.ConnectionString = string.Format(sdt.ConnectionString, "UserName""Password");
 <form id="form1" runat="server">                
            ConnectionString="<%$ ConnectionStrings:LocalSqlServer %>" 
            runat="server" />


Anonymous said...

Thanks very much! I was looking for another way to do this and also found this solution:

Anonymous said...

Perfect !!!!!!!!



iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...