山寨一个PetShop(Task002)——数据类库Model
源代码:13033480群共享
【操作步骤】
一、右击Web→添加新项Web配置文件
二、添加连接字符串
[html]
<connectionStrings>
<add name="SQLConnString1" connectionString="server=.\SQLEXPRESS;database=NetShop;integrated security=SSPI;min pool size=4;max pool size=4;" 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["SQLConnString1"].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(0), rdr.GetString(1), rdr.GetString(2));
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;
七、浏览并查看结果
【技术要点】
1、 连接字符串
2、 数据类库Model
3、IList、List
摘自 ASP.NET技术
补充:Web开发 , ASP.Net ,