您的位置:首页 > 其它

实验一:使用ADO.NET方式读数据

2016-11-03 08:32 246 查看
第一步:创建Asp.net应用程序

在VS中,点击文件->新建->项目,按如图方式选择并输入:





第二步:新建产品浏览网页窗体Listing.aspx:

在项目SportsStoreEx上点击右键,选中”添加“->”添加Web窗体“:



第三步:添加数据库

先点击下载SportStore数据库脚本,打开Sql Sever Managment Studio,登陆数据库服务器,在SSMS中打开SportStore数据库脚本,点击SSMS工具栏上的红色感叹号,运行脚本,SportStore数据库即建成,并有数据表Products,表中也有数据了。



第四步:在项目SportStoreEx中添加数据模型类Product:

右键点击项目SportStore,选中添加->类,输入类名:Product。

类Product用来描述数据库中的Products表中的记录,类代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SportStoreEx
{
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }

public string Category { get; set; }
public decimal Price { get; set; }
}
}


第五步:添加GetProducts()方法

双击Listing.aspx.cs文件,在Listing类里添加GetProducts()方法,代码如下:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SportStoreEx
{
public partial class Listing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected IEnumerable<Product> GetProducts()
{
IList<Product> products = new List<Product>();

string sql = "select ProductID,Name,Description,Category,Price from Products";
var con = new SqlConnection("Data Source=.;Initial Catalog=SportsStore;Integrated Security=True");
var cmd = new SqlCommand(sql, con);
SqlDataReader dr;

con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var prod = new Product();
prod.ProductID = dr.GetInt32(0);
prod.Name = dr.GetString(1);
prod.Description = dr.GetString(2);
prod.Category = dr.GetString(3);
prod.Price = dr.GetDecimal(4);
products.Add(prod);
}
return products;
}
}
}


第六步:修改Listing.aspx文件:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Listing.aspx.cs" Inherits="SportStoreEx.Listing" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%foreach (SportStoreEx.Product prod in GetProducts())
{
Response.Write("<div class='item'>");
Response.Write(string.Format("<h3>{0}</h3>",prod.Name));
Response.Write("</div>");
}
%>
</div>
</form>
</body>
</html>


第七步:运行代码。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: