Bind DataSource Using Config File Connection Strin

2019-08-28 22:18发布

问题:

I have a Connection String defined in my web.config file. I use this connection string in the code itself. However, for DataSources (bound to dropdown lists) I select it using the Data Source Configuration process. This causes a separation that means, if the connection string changes, I have to change it in more than one place.

Is there a way to refer to the web.config connection string with the DataSources on the dropdown lists?

回答1:

You need this. ;)

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer %>" SelectCommand="SPNAME" SelectCommandType="StoredProcedure">
                <SelectParameters>
                    <asp:Parameter Name="Id" Type="Int32" />
                </SelectParameters>
            </asp:SqlDataSource>

for get all connection strings in Dropdownlist:

  foreach (var s in System.Web.Configuration.WebConfigurationManager.ConnectionStrings)  {
    Response.Write(s);  }