ASP.NET Tutorial/Configuration/ConfigurationManager

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Load connection string from ConfigurationManager

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="FromConfig" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Connection String from Config</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:Button ID="Button1" runat="server" Text="Go get data..." OnClick="Button1_Click" />

       <asp:DropDownList runat="server" ID="CustomerList" />
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class FromConfig : System.Web.UI.Page {

   protected void Button1_Click(object sender, EventArgs e)
   {
       string connString = ConfigurationManager.ConnectionStrings["LocalNWind"].ConnectionString;
       using (SqlConnection conn = new SqlConnection(connString))
       {
           string cmdText = "SELECT * FROM customers";
           SqlCommand cmd = new SqlCommand(cmdText, conn);
           cmd.Connection.Open();
           SqlDataReader reader = cmd.ExecuteReader();
           CustomerList.Items.Clear();
           while (reader.Read())
               CustomerList.Items.Add(reader["companyname"].ToString());
           reader.Close();
            cmd.Connection.Close();
       }
   }

} File: Web.config <?xml version="1.0"?> <configuration> ...

 <connectionStrings>
   <add name="LocalNWind" connectionString="SERVER=(local);DATABASE=northwind;Trusted_Connection=yes;" />
 </connectionStrings>

... </configuration></source>