First step: Create an ASP.
In VS, click on New project, file----select and type by way:
Step Two: New product Browse Web Form listing.aspx:
Right-click on the project Sportsstoreex and select Add Web Form:
Step three: Add a database
Click the download sportstore database script, open the SQL Sever Managment Studio, log in to the database server, open the Sportstore database script in SSMs, click the red exclamation mark on the SSMs toolbar, run the script, Sportstore database is built, and there are data table products, the table also has data.
Fourth step: Add the Data Model class product in the project Sportstoreex:
Right-click on item sportstore, check Add-in class, enter class name: Product.
Class product is used to describe the records in the Products table in the database, and the class code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;namespacesportstoreex{ Public classProduct { Public intProductID {Get;Set; } Public stringName {Get;Set; } Public stringDescription {Get;Set; } Public stringCategory {Get;Set; } Public decimalPrice {Get;Set; } }}
Fifth step: Add the GetProducts () method
Double-click the Listing.aspx.cs file and add the GetProducts () method to the listing class with the following code:
usingSystem;usingSystem.Collections.Generic;usingSystem.Data.SqlClient;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;namespacesportstoreex{ Public Partial classListing:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) { } protectedIenumerable<product>getproducts () {IList<Product> products =NewList<product>(); stringsql ="Select Productid,name,description,category,price from Products"; SqlConnection Con=NewSqlConnection ("Data Source=.;i Nitial catalog=sportsstore;integrated security=true"); SqlCommand cmd=NewSqlCommand (sql, con); SqlDataReader Dr; Con. Open (); Dr=cmd. ExecuteReader (); while(Dr. Read ()) {Product prod=NewProduct {ProductID= Dr. GetInt32 (0), Name= Dr. GetString (1), Description= Dr. GetString (2), Category= Dr. GetString (3), price= Dr. Getdecimal (4) }; Products. ADD (PROD); } returnProducts ; } }}
Sixth step: Modify the Listing.aspx file:
<%@ Page language="C #"autoeventwireup="true"Codebehind="Listing.aspx.cs"inherits="sportstoreex.listing"%><! DOCTYPE html>"http://www.w3.org/1999/xhtml">"Server"><meta http-equiv="Content-type"Content="text/html; Charset=utf-8"/> <title></title>"Form1"runat="Server"> <div> <%foreach(Sportstoreex.product prodinchgetproducts ()) {Response.Write ("<div class= ' item ' >"); Response.Write (string. Format ("", prod. Name)); Response.Write ("</div>"); } %> </div> </form></body>Seventh Step: Run the code.
Experiment one: Using ADO to read data