山寨一个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";
相关新闻>>
- 发表评论
-
- 最新评论 更多>>