ASP.NET学习之分页数据绑定_GridView
前台页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView自定义真分页.aspx.cs" Inherits="分页显示数据.GridView自定义真分页" %> <!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> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateField HeaderText="用户ID"> <ItemTemplate><%#Eval("Uid") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="主题"> <ItemTemplate><%#Eval("Subject") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="内容"> <ItemTemplate><%#Eval("Content") %></ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 总共有<asp:Label ID="TRecordCount" runat="server"></asp:Label>条数据 每页记录<asp:Label ID="TPageSize" runat="server"></asp:Label>条数据 共有<asp:Label ID="TPageCount" runat="server"></asp:Label>页数据 当前是第<asp:Label ID="numberPage" runat="server"></asp:Label>页 <asp:LinkButton ID="First" runat="server" CommandName="first" OnCommand="First_Command">首页</asp:LinkButton> <asp:LinkButton ID="Pre" runat="server" CommandName="pre" OnCommand="First_Command">上一页</asp:LinkButton> <asp:LinkButton ID="Next" runat="server" CommandName="next" OnCommand="First_Command">下一页</asp:LinkButton> <asp:LinkButton ID="Last" runat="server" CommandName="last" OnCommand="First_Command">尾页</asp:LinkButton> 直接跳到第<asp:DropDownList ID="ddl" runat="server" OnSelectedIndexChanged="ddl_SelectedIndexChanged"> </asp:DropDownList>页 </div> </form> </body> </html>
后台代码:
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Text; namespace 分页显示数据 { /// <summary> /// GridView自定义真分页 /// 准备工作: /// 1、前台准备 /// 1)添加一个GridView组件。可以根据需求设置行列。也可以设置GridView1.AutoGenerateColumns = true;来默认生成行列 /// 2)把需要的组件都准备好【显示总页数、总记录数、每页显示的数据数、当前页数、上一页、下一页、首页、尾页、下拉选项】 /// /// 2、后台准备 /// 1)申明四个变量:用来存储总页数、总记录数、每页数据数、当前页数 /// 2)定义一个方法:用来获取所有数据,通过SQLDataAdapter将数据填充到DataSet中 /// 3)在程序第一次加载的时候,给总页数、总记录数、每页显示的数据数、当前页数和下拉选项赋值 /// 4)写一个方法来拼接【查询每个页面要显示的数据】的SQl语句 /// 5)写一个方法:在该方法中通过调用Sql语句拼接的方法,得到每个页面要显示的数据 /// 6)写一个方法:用来实现当页码发生改变时,显示每页的数据【主要是数据绑定、按钮是否可用的设置】 /// 7)首页、上一页、下一页、尾页点击事件的实现方法:四个用一个点击方法 /// 8)给下拉选项的选项改变写事件 /// /// </summary> public partial class GridView自定义真分页 : System.Web.UI.Page { private int PageCount; //总页数 private int RecordCount; //总记录数 private int PageSize=5; //初始化每页的数据量//每页显示多少条数据 private int CurrentPageIndex; //当前是第几页 string strConnection = ConfigurationManager.ConnectionStrings["MyDB"].ToString(); //获得数据库连接字符串 /// <summary> /// 加载页面 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { #region 第一次加载 if (!IsPostBack) { //第一次加载:在第一加载时初始化的数据,在之后的操作中都不会改变 //初始化PageCount、RecordCount、PageSize DataSet ds=GetDataSet(); RecordCount = ds.Tables[0].Rows.Count; //得到数据的总记录数 //给页数赋值 if (RecordCount % PageSize == 0) { //如果总记录数取余每页显示的条数,结果是0,说明刚好除尽。 PageCount = RecordCount / PageSize; } else { //否则没有除尽 PageCount = RecordCount / PageSize + 1; } CurrentPageIndex = 1; //当前页 //用lable记下这几个值,就不需要每次都计算一遍了。直接用就可以了 TRecordCount.Text = RecordCount.ToString(); TPageCount.Text = PageCount.ToString(); TPageSize.Text = PageSize.ToString(); numberPage.Text = CurrentPageIndex.ToString(); //给ddl组件[下拉组件]绑定数据 for (int i = 1; i <= PageCount; i++) { ddl.Items.Add(i.ToString()); } //根据页码展示数据 ShowData(); } #endregion CurrentPageIndex = int.Parse(numberPage.Text.ToString()); //得到当前页码,赋给CurrentPageIndex PageCount = int.Parse(TPageCount.Text.ToString()); //获得页码总数 } /// <summary> /// 得到查询的表的所有数据,通过SQLDataAdapter填充到DataSet中【方便给四个主要变量赋值】 /// </summary> public DataSet GetDataSet() { DataSet ds = new DataSet(); using (SqlConnection sqlConn = new SqlConnection(strConnection)) { //创建数据库链接对象 string sqlStr = "select Uid,Subject,Content from tb_leaveWord"; //SQL查询语句 SqlDataAdapter sda = new SqlDataAdapter(sqlStr, sqlConn); //将满足条件的数据填充到ds集合中 sda.Fill(ds); } return ds; } /// <summary> /// 得到每页的数据 /// </summary> /// <returns></returns> public DataSet GetEveryPageData() { DataSet ds = new DataSet(); using (SqlConnection sqlconn = new SqlConnection(strConnection)) { string str = GetSqlStr(); SqlDataAdapter sda = new SqlDataAdapter(str, sqlconn); sda.Fill(ds); } return ds; } /// <summary> /// 得到Sql语句 /// </summary> /// <returns></returns> public string GetSqlStr() { #region 方法一: StringBuilder sb = new StringBuilder(); sb.Append("select top("); sb.Append(PageSize.ToString()); sb.Append(")Uid,Subject,Content from tb_LeaveWord where ID not in((select top("); sb.Append((PageSize * (CurrentPageIndex - 1)).ToString()); sb.Append(")ID from tb_LeaveWord))"); return sb.ToString(); #endregion #region 方法二: //StringBuilder sb = new StringBuilder(); //sb.AppendFormat("select top({0})Uid,Subject,Content from tb_LeaveWord where ID not in((select top({1})ID from tb_LeaveWord))", PageSize.ToString(), (PageSize * (CurrentPageIndex - 1)).ToString()); //return sb.ToString(); #endregion #region 方法三:不建议这么写 //string str = "select top(" + PageSize.ToString() + ")Uid,Subject,Content from tb_LeaveWord where ID not in((select top(" + (PageSize * (CurrentPageIndex - 1)).ToString() + ")ID from tb_LeaveWord))"; #endregion } /// <summary> /// 显示选定页码该显示的数据 /// </summary> public void ShowData() { DataSet Sds = GetEveryPageData(); GridView1.DataSource = Sds; //先要让数据按照自己给定的行列显示数据,那就把该属性关掉【这样就不会出现默认生成的行列了】 //GridView1.AutoGenerateColumns = true; GridView1.DataBind(); numberPage.Text = CurrentPageIndex.ToString(); ddl.SelectedValue = CurrentPageIndex.ToString(); //下拉菜单选择中的值 //设置按钮的可用性 if(CurrentPageIndex==1){ First.Enabled = false; Pre.Enabled = false; } else { First.Enabled = true; Pre.Enabled = true; } if (CurrentPageIndex==PageCount) { Next.Enabled = false; Last.Enabled = false; } else { Next.Enabled = true; Last.Enabled = true; } } /// <summary> /// 下拉框选项改变事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ddl_SelectedIndexChanged(object sender, EventArgs e) { string num = ddl.SelectedValue; CurrentPageIndex = int.Parse(num); ShowData(); } /// <summary> /// 写首页、上一页、下一页、尾页点击事件的实现方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void First_Command(object sender, CommandEventArgs e) { string result = e.CommandName; switch(result){ case "first": CurrentPageIndex = 1; break; case "pre": CurrentPageIndex--; break; case "next": CurrentPageIndex++; break; case "last": CurrentPageIndex = PageCount; break; } ShowData();//数据展示 } } }