Friday, January 2, 2009

How to do paging in grid view .NET?

There could be many records from data source that needs to be rendered in grid view.

In such case, it does not look good to load all records in one page which gives a very long vertical scroll bar.
Also loading all records at once through grid view takes more time to render content onto browser.

In such case there is an option saying AllowPaging="true", which enables paging option.
PageSize atrribute is to set the total records that has to be displayed in each page.
OnPageIndexChanging event has to be handled, such that each time when user clicks on specific page index corresponding indexed records has to be binded.
This can be done by just specifying the page index of the grid.

Aspx page :-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
<link href="Styles/Stylesheet.css" rel="stylesheet" type="text/css" />

<form id="form1" runat="server">
<asp:GridView ID="grdData" runat="server" CssClass="grid_td" Width="40%" AutoGenerateColumns="false" OnRowDataBound="grdData_RowDataBound" AllowPaging="true" PageSize="4" OnPageIndexChanging="grdData_PageIndexChanging" >
<HeaderTemplate >Name</HeaderTemplate>
<asp:Label ID="lblName" Text='<%#Eval("Name")%>' runat="server"></asp:Label>
<asp:LinkButton ID="lnk" runat="server">Link</asp:LinkButton>


Code behind page:-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
private void BindGrid()
DataTable dt = new DataTable();
DataRow dr = null;
for (int i = 1; i <= 10; i++)
dr = dt.NewRow();
dr["Name"] = i.ToString();
grdData.DataSource = dt;

//Row data bound event function
protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
//For each row from data source when bounded to grid this event is raised
LinkButton lnk = e.Row.FindControl("lnk") as LinkButton;
Label lblName = e.Row.FindControl("lblName") as Label;
//checking the controls found from each row based on id is null or nut
if (lnk != null && lblName != null)
//Adding java script alert box to display associated name on the corresponding label
lnk.Attributes.Add("onclick","alert('"+lblName.Text+"'); return false;");
//Handling page index change event
protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
//setting new page index to the gird based upon user clicked index
grdData.PageIndex = e.NewPageIndex;
//Binding the data source again after assigning new page index


No comments:

Post a Comment