此前已经介绍了怎样用GridView自身的分页功能实现了分页,但它用户自定义的功能很弱下面我们介绍用PagedDataSource对象实现分页,可以说他可以是一个通用的,在之前我们已经介绍了用它来实现datalist的分页功能,方法几乎一样,就不多说了现在只看实例代码:
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
{
static string sqlconn = "server=.;uid=sa;pwd=;database=StudentSystem";
SqlConnection conn = new SqlConnection(sqlconn);
PagedDataSource ps = new PagedDataSource();
static int count; //用来表示总页数,一定要定义为全局的
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //假如是页面首次加载
{
ViewState["PageIndex"] = "0"; //ViewState["pageindex"] 是用来控制PagedDataSource的当前页的,用来表示当前显示页的索引号,也可以用一个全局变量来指示当前页的索引
BindData();
}
}
private void BindData()
{
ps.AllowPaging = true;
ps.PageSize = 10; //定义分页的初始化状态
ps.CurrentPageIndex = int.Parse(ViewState["PageIndex"].ToString());
conn.Open();
DataSet ds = CreateDataSet();
ps.DataSource = ds.Tables[0].DefaultView; //把数据源交给PagedDataSource对象,让它完成分页
GridView1.DataSource = ps;
GridView1.DataBind();
conn.Close();
count = int.Parse(ps.PageCount.ToString()); //注意一定要写在这个位置,即在PagedDataSource有数据之后,千万别写在初始化状态时
//Label6.Text = count.ToString(); //显示总页数
//Label5.Text = Convert.ToInt32((ps.CurrentPageIndex + 1)).ToString(); //显示当前页
if (ps.CurrentPageIndex == 0)
{
Lnkbtn_Prev.Enabled = false;
Lnkbtn_Next.Enabled = true;
} //控制显示按钮,最好写在加载数据的bind函数里面
else if (ps.CurrentPageIndex == count - 1)
{
Lnkbtn_Prev.Enabled = true;
Lnkbtn_Next.Enabled = false;
}
else
{
Lnkbtn_Prev.Enabled = true;
Lnkbtn_Next.Enabled = true;
}
}
protected void IndexChanging(object sender, EventArgs e)
{
string strCommand = ((LinkButton)sender).CommandArgument.ToString();
int pageindex = int.Parse(ViewState["PageIndex"].ToString());//当前页
if (strCommand == "上")
pageindex = pageindex - 1;
else if (strCommand == "下")
pageindex = pageindex + 1; //判断是哪个LinkButton被触发
else if (strCommand == "首页")
pageindex = 0;
else if (strCommand == "尾页")
pageindex = count - 1;
ViewState["PageIndex"] = pageindex; //重新把修改了的页码付给当前页,必不可少
BindData();
}
private DataSet CreateDataSet()
{
string strsql = "select * from studentinfo";
SqlCommand cmd = new SqlCommand(strsql, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
<asp:LinkButton ID="Lnkbtn_Top" runat="server" CommandArgument="首页" OnClick="IndexChanging">首页</asp:LinkButton>
<asp:LinkButton ID="Lnkbtn_Prev" runat="server" CommandArgument="上" OnClick="IndexChanging">上</asp:LinkButton>
<asp:LinkButton ID="Lnkbtn_Next" runat="server" CommandArgument="下" OnClick="IndexChanging">下</asp:LinkButton>
<asp:LinkButton ID="Lnkbtn_Last" runat="server" CommandArgument="尾页" OnClick="IndexChanging">尾页</asp:LinkButton>