写出代码之前,先说明一下原理,比较简单。有一张表(test)如下
结构是:id(自动编号) txt 假设40条记录)
现在要每页显示10条记录,则每页要显示的数据应该是:
第一页:1----10
第二页:11----20
第三页:21----30
第四页:31----40
如要显示第一页,最简单的方法就是 select top 10 * from test 就OK了。
第二页开始呢?怎么做呢?请接着看:
比如我要显示第三页:也就是21----30
原理:找出不要的数据也就是1----20,最大的id,这是里20
再找出大于这个id(20) 前10条记录就OK了。
原理知道后写代码就简单了,前台界面比较简单,不多说,代码如下
<asp:LinkButton id="lbtnFirst" Runat="server">首頁</asp:LinkButton>
<asp:LinkButton id="lbtnBack" Runat="server">上頁</asp:LinkButton>
<asp:LinkButton id="lbtnNext" Runat="server">下頁</asp:LinkButton>
<asp:LinkButton id="lbtnLast" Runat="server">尾頁</asp:LinkButton>
<asp:Label id="Label1" runat="server">当前页:</asp:Label>
<asp:Label id="lblCurrentPage" runat="server">1</asp:Label>
<asp:Label id="Label2" runat="server">总页:</asp:Label>
<asp:Label id="lblPageCount" runat="server">200</asp:Label>
<asp:Label id="Label3" runat="server">跳转:</asp:Label>
<asp:TextBox id="txtToPage" runat="server" Width="88px"></asp:TextBox>
<asp:Button id="btnToPage" runat="server" Text="go"></asp:Button>
<asp:DataGrid id="DataGrid1" runat="server" AllowPaging="True" AllowCustomPaging="True"></asp:DataGrid>
后台代码:private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//开始显示第一页
ShowDate(Convert.ToInt64(lblCurrentPage.Text));
}
}
/// <summary>
/// 显示数据
/// </summary>
/// <param name="page"></param>
private void ShowDate(long page)
{
/*-------------------设置参数------------------*/
string tblName = "test";
string fldName = "id";
string orderStr = "asc";
int PageSize = 10;
/*-------------------设置结束------------------*/
byte[] t =Convert.FromBase64String(System.Configuration.ConfigurationSettings.AppSettings["conStr"]);
string conStr = System.Text.ASCIIEncoding.ASCII.GetString(t);
SqlConnection conn = new SqlConnection(conStr);
conn.Open();
SqlCommand cmd = new SqlCommand("select count(*) from " + tblName,conn);
lblPageCount.Text = Convert.ToString(((int)cmd.ExecuteScalar() / PageSize + 1));
DataGrid1.VirtualItemCount = Convert.ToInt32(lblPageCount.Text);//datadrid每次就显示一页,所有要手动加上总页
string sql = string.Empty;
sql = "select top " + Convert.ToString((page - 1) * PageSize) + " " + fldName + " from " + tblName + " order by " + fldName + " " + orderStr; //排除的记录部分
sql = "select max (" + fldName + ") from ( " + sql + " ) as t"; //得到排除记录里的最大ID号
sql = "select top " + PageSize.ToString() + " * from " + tblName + " where " + fldName + ">(" + sql + ") order by " + fldName + " " + orderStr;
if (page == 1){sql = "select top " + PageSize + " * from " + tblName;lblCurrentPage.Text = "1";}
try
{
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
System.Data.DataSet ds = new DataSet();
da.Fill(ds);
DataGrid1.DataSource = ds.Tables[0].DefaultView;
DataGrid1.DataBind();
conn.Close();
}
catch ( Exception ex)
{
Response.Write(ex.Message.ToString());
}
}