先定义ASPX页面,注意AllowCustomPaging要设为"False":
<asp:datagrid id="MyDataGrid" runat="server" Width="100%" PageSize="20" AllowPaging="True" AutoGenerateColumns="False" DataKeyField="FDictid">
<Columns>
</Columns>
<PagerStyle Visible="False"></PagerStyle>
</asp:datagrid>
<asp:linkbutton id="btnFirst" runat="server" CommandArgument="fist">首页</asp:linkbutton>
<asp:linkbutton id="btnPrev" runat="server" Width="36px" CommandArgument="prev">上一页</asp:linkbutton>
<asp:linkbutton id="btnNext" runat="server" CommandArgument="next">下一页</asp:linkbutton>
<asp:linkbutton id="btnLast" runat="server" CommandArgument="last">末页</asp:linkbutton>
<asp:label id="lblCurrentIndex" runat="server"></asp:label>/<asp:label id="lblPageCount" runat="server"></asp:label>
跳转到<asp:TextBox id="txtGoPage" runat="server" Width="30px" CssClass="textbox"></asp:TextBox>
<asp:Button id="btnGo" runat="server" Text="GO" CssClass="button" Width="29px"></asp:Button>
CODE:
public void BindGrid()
{
string strSql ="SELECT * FROM t_dict ";
SqlDataAdapter myCommand = new SqlDataAdapter(strSql, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "t_dict");
MyDataGrid.DataSource=ds.Tables["t_dict"].DefaultView;
MyDataGrid.DataBind();
ShowStatsPage();
}
private void PagerButtonClick(object sender, System.EventArgs e)
{
//获得LinkButton的参数值
String arg = ((LinkButton)sender).CommandArgument;
switch(arg)
{
case ("next"):
if (MyDataGrid.CurrentPageIndex < (MyDataGrid.PageCount - 1))
MyDataGrid.CurrentPageIndex ++;
break;
case ("prev"):
if (MyDataGrid.CurrentPageIndex > 0)
MyDataGrid.CurrentPageIndex --;
break;
case ("fist"):
MyDataGrid.CurrentPageIndex=0;
break;
case ("last"):
MyDataGrid.CurrentPageIndex = (MyDataGrid.PageCount - 1);
break;
default:
//本页值
MyDataGrid.CurrentPageIndex = Convert.ToInt32(arg);
break;
}
BindGrid();
}
void ShowStatsPage()
{
//显示页面信息
lblCurrentIndex.Text = "[<font color="blue">当前为第:" + ((int)MyDataGrid.CurrentPageIndex+1) + "页</font>]";
lblPageCount.Text = "[<font color="blue">共:" + MyDataGrid.PageCount + "页</font>]";
}
private void MyDataGrid_PageIndExchanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
//处理按下数字的方法
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
BindGrid();
}
private void btnGo_Click(object sender, System.EventArgs e)
{
//页面直接跳转的代码
if(txtGoPage.Text.Trim()!="")
{
int PageI=Int32.Parse(txtGoPage.Text.Trim())-1;
if (PageI >=0 && PageI < (MyDataGrid.PageCount))
MyDataGrid.CurrentPageIndex = PageI ;
}
BindGrid();
}
//----------------------翻页代码结束