Question

sorry if this is dummy question but it really freak me out.

I have set the connection string in web.conf

<appSettings>
<add key="DBHost" value="myserver.com"></add>
<add key="DBName" value="myDBName"></add>
<add key="DBLogin" value="myDBLogin"></add>
<add key="DBPassword" value="myDBPass"></add>
<!--DBTrustedConnection: true then Connection string will be used else user and password is required-->
<add key="DBTrustedConnection" value="true"></add> 
<add key="DBConnectionString" value="Data source=.\sqlexpress; Initial Catalog=DQMF; Integrated Security=True"></add>
.....other settings
</appSettings>

here is the code i am trying to use

 <form id="form1" runat="server">
    <% string con=""; 
       if(System.Configuration.ConfigurationManager.AppSettings.Get("DBTrustedConnection").Equals("true"))
           con = System.Configuration.ConfigurationManager.AppSettings.Get("DBConnectionString");
       else { 
           string DBHost = System.Configuration.ConfigurationManager.AppSettings.Get("DBHost");
           string DBName = System.Configuration.ConfigurationManager.AppSettings.Get("DBName");
           string DBLogin = System.Configuration.ConfigurationManager.AppSettings.Get("DBLogin");
           string DBPassword = System.Configuration.ConfigurationManager.AppSettings.Get("DBPassword");
           con = "Data Source=" + DBHost + ";Initial Catalog=" + DBName + ";User ID=" + DBLogin + ";Password=" + DBPassword + ";";
       }
      %>
    <asp:SqlDataSource runat="server" ConnectionString="<%=con %>??? How to use con variable here" SelectCommand="SELECT COMMAND" ID="SqlDataSource1"></asp:SqlDataSource>

The problem here is i am not able to use the con variable . please help me or suggest some other way as i am completely new to asp

Was it helpful?

Solution 2

Move Your code in the code behind, then pass Your connection string to datasource

OTHER TIPS

In Web.Config, there is a tag, If it is not there then add it after the </appSettings>:

</appSettings>
<connectionStrings>
     <add name="name" connectionString="Data source=.\sqlexpress; Initial Catalog=DQMF; Integrated Security=True"/>
</connectionStrings>

and to get Connection String, use the following code(Use Code Behind in some event like Page_Load):

protected void Page_Load(object sender, EventArgs e)
{
    string connectionString = 

    System.Configuration.ConfigurationManager.ConnectionStrings["name"].ConnectionString;

    if(!string.IsNullOrEmpty(connectionString))
    {
         //Use it here...
         SqlDataSource1.ConnectionString = connectionString;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top