简单实用的DataGrid自定义分页源程序_[Asp.Net教程]
首先新建一个名为article.aspx的文件,将以下内容拷贝到article.aspx.cs中:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 article : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int cpage = Convert.ToInt32(Request.QueryString["page"]);
if(cpage==0)
{
this.hlFrontPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"];
this.hlNextPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page=" + Convert.ToString(cpage + 2);
}
else
{
this.hlFrontPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page=" + Convert.ToString(cpage - 1);
this.hlNextPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page=" + Convert.ToString(cpage + 1);
}
this.hlFirstPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"];
dataBin();
//***************************************************
//PageCount的值必须在数据绑定之后才能得到,否则只能是0
//***************************************************
int lastPage =this.DataGrid1.PageCount;//lastPage是记录总页数
this.hlLastPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page="+Convert.ToInt32(lastPage);
if (cpage ==Convert.ToInt32(this.DataGrid1.PageCount))
{
this.hlNextPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page=" + Convert.ToString(lastPage);
this.hlFrontPage.NavigateUrl = Request.ServerVariables["SCRIPT_NAME"] + "?page=" + Convert.ToString(cpage - 1);
}
this.lbShowMess.Text= "当前第"+Convert.ToInt32(this.DataGrid1.CurrentPageIndex+1)+"页";
}
public void dataBin()
{
DB mydb = new DB();
SqlConnection conn = mydb.createConn();
conn.Open();
SqlDataAdapter sdr = new SqlDataAdapter();
DataSet ds = new DataSet();
sdr.SelectCommand = new SqlCommand("select * from [User]", conn);
sdr.Fill(ds, "users");
int page=Convert.ToInt32(Request.QueryString["page"]);
if (page == 0)
{
page = 1;
}
this.DataGrid1.CurrentPageIndex =Convert.ToInt32(page-1);
this.DataGrid1.DataSource = ds.Tables["users"];
this.DataGrid1.DataBind();
conn.Close();
}
protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
}
}
再将以下内容拷贝到article.aspx中
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="article.aspx.cs" Inherits="article" %>
无标题页