C# GridView Paging

4/1/2014·2 min read

In ASP.NET, if you could imprement paging, .NET has build-in function which you could easily build tables has paging. Therefore, here is trying to show how to make easy sample possible. However, you have to remember, you have to be careful to use, since .NET'll use ViewState, and their build-in javascript library which enable you to "post back" to your server side and ViewState might end up like lots information stay on your client.

GridView Paging


1. how aspx page looks

remeber to add event on your gridview, which is pageindexchanging, if you don't and run the page, it'll throw exception error.

     <asp:GridView  ID="GridView1"  runat="server"  AllowPaging="True"
 		 onpageindexchanging="GridView1_PageIndexChanging"  PageSize="4">

2. page load event

So, on page load section, assume you load data from your business logic layer, between page's post, you could use ViewState to maintain your state.

 		protected  void  Page_Load(object  sender, EventArgs  e)
 			if  (!IsPostBack)
 				ViewState["mydata" ] = Class1 .GetData();
 				this .GridView1.DataSource = ViewState["mydata" ];
 				this .GridView1.DataBind();
 				this .GridView2.DataSource = ViewState["mydata" ];
 				this .GridView2.DataBind();

3. paging event

On paging event, load data from ViewState, changing the paging's index.

 	protected  void  GridView1_PageIndexChanging(object  sender, GridViewPageEventArgs  e)
 			if  (ViewState["mydata" ] != null )
 				this .GridView1.DataSource = (List <Product >)ViewState["mydata" ];
 				this .GridView1.PageIndex = e.NewPageIndex;
 				this .GridView1.DataBind();

If you check the HTML source, you actually didn't get page you need to display to UI, didn't dump entire data to the page.

HTML Source


Inclusion, good thing for this, you could control on each of the paging event, include what's data you want to display to UI. bad thing, it's you need to find way to maintain state, this example is using viewstate, you have to be careful, since remeber your viewstate might be huge files. Also, have to go back to server to do paging.