You can attach ChangePage event to both Button , then get current page, and do calculations to get previous and next page.
<asp:Button ID="Btn_Previous" CommandName="Previous"
runat="server" OnCommand="ChangePage"
Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next"
OnCommand="ChangePage" Text="Next" />
protected void ChangePage(object sender, CommandEventArgs e)
{
int pageNumber = gvCustomers.PageIndex;
switch (e.CommandName)
{
case "Previous":
if (pageNumber > 0)
{
gvCustomers.PageIndex = pageNumber - 1;
}
break;
case "Next":
gvCustomers.PageIndex = pageNumber + 1;
break;
}
this.BindGrid();
}
You can refer to the following demo:
<div>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="gvCustomers_OnPageIndexChanging"
PageSize="5">
<Columns>
<asp:BoundField DataField="StudentId" HeaderText="StudentId" />
<asp:BoundField DataField="StudentName" HeaderText="StudentName" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
<asp:Button ID="Btn_Previous" CommandName="Previous"
runat="server" OnCommand="ChangePage"
Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next"
OnCommand="ChangePage" Text="Next" />
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Student", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
protected void gvCustomers_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void ChangePage(object sender, CommandEventArgs e)
{
int pageNumber = gvCustomers.PageIndex;
switch (e.CommandName)
{
case "Previous":
if (pageNumber > 0)
{
gvCustomers.PageIndex = pageNumber - 1;
}
break;
case "Next":
gvCustomers.PageIndex = pageNumber + 1;
break;
}
this.BindGrid();
}
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.