【操作步驟】
一
右擊Web→添加新項Web配置文件
二
添加連接字符串
[html]
<connectionStrings>
<add name=
SQLConnString
connectionString=
server=
\SQLEXPRESS;database=NetShop;integrated security=SSPI;min pool size=
;max pool size=
;
providerName=
System
Data
SqlClient
/>
</connectionStrings>
三
復制Model中的CategoryInfo
c
四
Default
aspx中添加控件ListBox
[html]
<div>
<asp:ListBox ID=
lstCategories
runat=
server
>
</asp:ListBox>
</div>
五
Default
aspx
cx中添加如下代碼
[csharp]
public partial class _Default : System
Web
UI
Page
{
private const string SQL_SELECT_CATEGORIES =
SELECT CategoryId
Name
Descn FROM Category
;
protected void Page_Load(object sender
EventArgs e)
{
IList<CategoryInfo> categories = new List<CategoryInfo>()
//數據庫基本操作
String connectionString = ConfigurationManager
ConnectionStrings[
SQLConnString
]
ConnectionString;
SqlCommand cmd = new SqlCommand()
SqlConnection conn = new SqlConnection(connectionString)
conn
Open()
cmd
Connection = conn;
cmd
CommandText = SQL_SELECT_CATEGORIES;
cmd
CommandType = CommandType
Text;
SqlDataReader rdr = cmd
ExecuteReader(CommandBehavior
CloseConnection)
//數據保存到Model中
while (rdr
Read())
{
CategoryInfo cat = new CategoryInfo(rdr
GetString(
)
rdr
GetString(
)
rdr
GetString(
))
categories
Add(cat)
}
conn
Close()
//數據綁定綁定到用戶界面
lstCategories
DataSource = categories;
lstCategories
DataTextField =
Name
;
lstCategories
DataValueField =
ID
;//Model中的字段與數據庫表中的字段一樣
是不是更好?
lstCategories
DataBind()
}
}
六
代碼中使用了List
ConfigurationManager
Model中的類
需要添加相應的引用
並導入相應的命名空間
using System
Collections
Generic;
using System
Configuration;
using NetShop
Model;
七
浏覽並查看結果
【技術要點】
連接字符串
數據類庫Model
IList
List
From:http://tw.wingwit.com/Article/program/net/201311/13969.html