在项目中新建Default.aspx页面
html:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>数据绑定并实现分页功能</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="1" cellpadding="0" cellspacing="0" style="font-size: 9pt;
403px; color: #ff0000; height: 132px; text-align: center">
<tr>
<td>
查看商品信息</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="4" ForeColor="#333333"
GridLines="None" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Right" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
CS:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon;
string strCon = "Data Source=in-zyz;Database=db_04;Uid=sa;Pwd=123";
protected void Page_Load(object sender, EventArgs e)
{
string sqlstr = "select GoodsID as 商品ID,GoodsName as 商品名称,GoodsIntroduce as 商品介绍,"
+ "GoodsPrice as 商品价格,GoodsIsNew as 是否推荐 from tb_GoodsInfo";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "tb_GoodsInfo");
GridView1.DataSource = myds;
GridView1.DataKeyNames = new string[] { "商品ID" };
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
}