开发者

How to use database connection strings in ASP.NET?

I've just started ASP.NET for real, and I was wondering if it is possible to use connection strings from Data Sources instead of hard-coding them. I've added my connection in Data Sources and it works, and I can also drag a table to a page in design mode, but I can't figure out how to access it in code. Here's what I get when I d开发者_开发问答rag it in:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="SqlDataSource1" 
    EmptyDataText="There are no data records to display.">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" 
            SortExpression="id" />
        <asp:BoundField DataField="xxx" HeaderText="xxx" 
            SortExpression="xxx" />
        <asp:BoundField DataField="xxx" HeaderText="xxx" 
            SortExpression="xxx" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:xxxConnectionString1 %>" 
    ProviderName="<%$ ConnectionStrings:xxxConnectionString1.ProviderName %>" 
    SelectCommand="SELECT xxx FROM xxx">
</asp:SqlDataSource>


I think your question is.. how do you access the connection string property that you see as

ConnectionString="<%$ ConnectionStrings:xxxConnectionString1 %>" in your aspx page right?

As Bala R mentioned...

use

ConfigurationManager.ConnectionStrings["xxxConnectionString1"].ToString();

but in order to do this, you should add the reference to System.Configuration.

i.e.

Imports System.Configuration


You can get the connection string in code behind like this

ConfigurationManager.ConnectionStrings["xxxConnectionString1"].ConnectionString;


The above posts are accurate, you'll want to explore the system.configuration assembly / namespace. text content can be stored in AppSettings or ConnectionStrings. its worth understanding how they both work moving forward.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜