Updated on Kisan Patel
This tutorial will explain you how to implement paginations to display records on the page using GridView in ASP.NET.
Default.aspx
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" OnPageIndexChanging="PaginateGridView" PageSize="2" PagerSettings-Mode="Numeric" />
In the above code, we have a GridView in the .aspx page with AllowPaging="true"
that will bring the Page numbers at the bottom of the GridView. Then we need to specify the number of records to show per page that can be set using PageSize property of the GridView. PagerSettings property allows us to set different mode of displaying the pagination.
Next, we need to handle the OnPageIndexChanging event and for this we have attached PaginateGridView server side method to fire.
Default.aspx.cs
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; namespace GridViewDemo { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private DataTable GetData() { DataTable table = new DataTable(); // get the connection using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { // write the sql statement to execute string sql = "SELECT Id, FirstName, LastName, Email, IsActive FROM Students"; // instantiate the command object to fire using (SqlCommand cmd = new SqlCommand(sql, conn)) { // get the adapter object and attach the command object to it using (SqlDataAdapter sdt = new SqlDataAdapter(cmd)) { // fire Fill method to fetch the data and fill into DataTable sdt.Fill(table); } } } return table; } protected void PaginateGridView(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.BindData(); } private void BindData() { // specify the data source for the GridView GridView1.DataSource = GetData(); // bind the data now GridView1.DataBind(); } } }
In the PaginateGridView method we have set the current page index of the GridView to the new Index as shown in above code.
Demo