Sunday 23 August 2009

ASP.NET Grid View Hidden Column Binding Problem

When I was using Grid View in my Web Application I run into problem where hidden column would not bind data. After searching I found a simple solution to this problem. Let’s have a look at example. We have a table called Person with columns ID, FirstName, Surname. In our page we want to show only FirstName and Surname columns and have ID column loaded but hidden.

For a Grid View component create RowCreated event handler with the code:

protected void GvRowCreated(object sender, GridViewRowEventArgs e)
{
    // Hide ID Column
    e.Row.Cells[0].Visible = false;
}

The code above will hide all cells in column Cells[0], which is ID column. If Grid View has paging enabled we need to check e.Row.RowType == DataControlRowType.DataRow to hide only Cells that contain data.