標籤:應用 blank new 表單 event rgs name 資料庫伺服器 data
第一步:建立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"; SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=SportsStore;Integrated Security=True"); SqlCommand cmd = new SqlCommand(sql, con); SqlDataReader dr; con.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { Product prod = new Product { ProductID = dr.GetInt32(0), Name = dr.GetString(1), Description = dr.GetString(2), Category = dr.GetString(3), 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>
第七步:運行代碼。
實驗一:使用ADO.NET方式讀資料