GridView DataBinding Events

This is a well commented example for a GridView with implementation of RowDataBound and DataBound events. I also demonstrate in it some of the important properties of GridView, like the slight differences when dealing with Grid Paging, Rows, Cells, and Columns. I prefered to heavily comment the code than to write separate paragraphs describing it as I do believe that the code is what gets the idea in a direct way.

The example is a simple page that uses SqlDataSource to connect to a SQL Server 2005 Express database and show the results on a GridView with paging capability.


Many parts of the code don’t show the best practices for their situation and those are only included for demonstration purpose as they are not the main focus of the example.

Let’s start with the code behind of the page:

As it’s the most important part

 * The sample is provided AS IS without any warranty
 * All rights reserved (C) 2005, Mohamed Meligy
 * Distribution of this code without this note is prohibited.
//Default "using" set of a new System.Web.UI.Page Visual Studio 2005 template:
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;
/// <summary>
/// To test the GridView behavior in action,
/// you need to have SQL Server Express installed (comes by default with VS2005),
/// and Northwind database attached to it
/// (attaches by default when you select "Quickstart Tutorials"
/// from the .NET Framework 2.0 SDK Programs menu, and choose to install them).
/// Alternatively, change the ConnectionString property of the SqlDataSource
/// to point to another installed instance
/// of SqlServer 2000 or SqlServer 2005 that has Northwind database attached.
/// </summary>
public partial class GridViewSamplePage : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        //Limiting redundancy of useless execution.
        //You do no need to check IsCallback if you
        // don't have controls with Callback Enabled.
        if (!IsPostBack & !IsCallback)
            //This makes performing paging and sorting uses AJAX.
            EmployeesGridView.EnableSortingAndPagingCallbacks = true;
            //Small number so that I can see many pages out of
            // 9 rows only (The total Rows Count of Northwind's Employees DataTable).
            //Also selected it in a way that last Page Rows Count will be
            // different than other pages.
            EmployeesGridView.PageSize = 2;
            if (!IsPostBack)   //Just to prove the AJAX thing.
                PostBackStatus.Text = "Not PostBack";
            else   //Never happens, as I don't require a PostBack.
                PostBackStatus.Text = "Page Is PostBack";
    /// <summary>
    /// Executes when the databinding is complete
    /// </summary>
    protected void EmployeesGridView_DataBound(object sender, EventArgs e)
        //I'll use it to show which set of Rows I'm showing in the page.
        EmployeesGridView.ShowFooter = true;
        //Similar to: EmployeesGridView.FooterRow.Visible = true
        //Stretching the first cell to fill the whole FooterRow:
        //Removing all non needed cells,
        // from the end to start
        // (so that the Cells collection is not recreated with every Removal).
        for (int cellNum = EmployeesGridView.Columns.Count - 1; cellNum > 0; cellNum--)
        EmployeesGridView.FooterRow.Cells[0].ColumnSpan = EmployeesGridView.Columns.Count;
        EmployeesGridView.FooterRow.Cells[0].HorizontalAlign = HorizontalAlign.Center;
        int startIndex = EmployeesGridView.PageIndex != EmployeesGridView.PageCount - 1 ?
        //Not in last page.
        EmployeesGridView.PageSize * EmployeesGridView.PageIndex
        //EmployeesGridView Rows Count is Count of the Rows of the current page, so,
            // unless Paging is Disabled, this is not total Rows Count.
            //gridViewTotalCount is declared and assigned at the end of this code.
        : gridViewTotalCount - EmployeesGridView.PageSize + EmployeesGridView.Rows.Count;
        EmployeesGridView.FooterRow.Cells[0].Text =
                ("Showing Employees {0} to {1} of {2}",
                startIndex + 1,
                startIndex + EmployeesGridView.Rows.Count, gridViewTotalCount);
    TableCell myCell = null;
    protected void EmployeesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        //I'll add that to every Row bound in the GridView.
        myCell = new TableCell();
        //Note that for the header, footer, and separator rows, DataItemIndex is -1
        myCell.Text = e.Row.DataItemIndex.ToString();
        //Note that when you add the cell,
        // this does NOT increase the GridView Columns Count.
        //The past lines will affect also HeaderRow, FooterRow, and even Pager,
        // you'll see when you run that this is not a desired behavior.
        //You can limit your code on condition. This is the recommended way.
        if (e.Row.RowType == DataControlRowType.DataRow)
            //Do your UI logic now for data binding,
            // much similar to DataGrid ItemDataBound.
            //Example: changing color of text
            // for normal and alternative rows ONLY by code.
            if (e.Row.RowIndex % 2 == 0)
                e.Row.Style["color"] = "#0000ff";
                e.Row.Style["color"] = "#00bb00";
            //This is the EmployeeID Cell
            e.Row.Cells[0].Text =
                "I'm alternative employee with code: " + e.Row.Cells[0].Text;
            //Another sample change making use of the DataItem:
            // This is specific to our case where the GridView is bound to
            // first DataTable in the DataSet returnd by the EmployeesSqlSource.
            // This is when SqlDataSource DataSourceMode = DataSet (Default)
            DataRowView rowView = (DataRowView)e.Row.DataItem;
            e.Row.Cells[EmployeesGridView.Columns.Count - 1].Text =
                int.Parse(rowView["Extension"] as string).ToString("###-##");
    int gridViewTotalCount;
    protected void EmployeesSqlSource_Selected
        (object sender, SqlDataSourceStatusEventArgs e)
        //GridView has no way of telling total Rows Count when paging is enabled.
        gridViewTotalCount = e.AffectedRows;

Now to the page XHTML source:

<%@ Page Language="C#" AutoEventWireup="true" 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">
<head id="PageHeader" runat="server">
    <title>GridView Sample</title>
    <form id="ServerForm" runat="server">
        Postback Status:
            <asp:Label ID="PostBackStatus" runat="server"></asp:Label>
            <asp:GridView ID="EmployeesGridView" runat="server"
                AutoGenerateColumns="False" AllowPaging="True"
                DataSourceID="EmployeesSqlSource" DataKeyNames="EmployeeID"
                    <asp:BoundField DataField="EmployeeID"
                        HeaderText="EmployeeID" InsertVisible="False"
                        ReadOnly="True" SortExpression="EmployeeID" />
                    <asp:BoundField DataField="LastName"
                        HeaderText="LastName" SortExpression="LastName" />
                    <asp:BoundField DataField="FirstName"
                        HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:BoundField DataField="Title"
                        HeaderText="Title" SortExpression="Title" />
                    <asp:BoundField DataField="BirthDate"
                        HeaderText="BirthDate" SortExpression="BirthDate" />
                    <asp:BoundField DataField="PostalCode"
                        HeaderText="PostalCode" SortExpression="PostalCode" />
                    <asp:BoundField DataField="Extension"
                        HeaderText="Extension" SortExpression="Extension" />
                    <div style="text-align: center">
                        No Data Available.
            <asp:SqlDataSource ID="EmployeesSqlSource" runat="server"
"Data Source=MELIGYSQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"
"SELECT [EmployeeID], [LastName], [FirstName], [Title], [BirthDate], [PostalCode], [Extension] FROM [Employees]"

Samples of the output of the code:

Hope that you like it.

Share With Friends:

How did I learn that?

As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.

It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.

Take it for a test ride, and you may unsubscribe any time.

You might also want to support me by checking these out [Thanks]: