ASP.NET Tutorial/Configuration/ConfigurationManager — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 11:57, 26 мая 2010
Load connection string from ConfigurationManager
<%@ 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">
<div>
<asp:Button ID="Button1" runat="server" Text="Go get data..." OnClick="Button1_Click" />
<hr />
<asp:DropDownList runat="server" ID="CustomerList" />
</div>
</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>