Free Information Technology Magazines and eBooks

Tuesday, January 17, 2012

ASP.NET: How To Add Paging On GridView Dynamically

Because of busy schedule on my day job, my last post was 10 day ago. To make up for it, I'll discuss an ASP.NET coding technique today. My topic is How to use paging in GridView control. First you have to set AllowPaging property to true as shown below.



And on the event "gridViewSample_PageIndexChanging" where gridViewSample is the name of your gridview, enter the following code after the jump.


protected void grdTruckListing_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
 gridViewSample.PageIndex = e.NewPageIndex;
 Session["mytable"] = LoadTable();

 gridViewSample.DataSource = Session["mytable"];
 gridViewSample.DataBind();
}

private DataTable LoadTable()
{
 //you can replace this with your own connection string and SQL command
 SqlConnection con = new SqlConnection(Settings.Default.ConnectionString);
 SqlCommand cmd = con.CreateCommand();
 cmd.CommandText = "spWeb_TruckMonitoring";
 cmd.CommandType = CommandType.StoredProcedure;
 DataTable tb = new DataTable();
 try
 {
   
  con.Open();
  tb.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));

 }
 catch (Exception ex)
 {
  Response.Write(ex.Message);
  Response.End();
 }

 return tb;
}

Just change the LoadTable() function with your own SQL command and your gridview will be Paging ready.


To stay up-to-date on Coding Tips & Tricks, subscribe now.

0 comments: