Archive for the ‘Server Controls’ Category

Format BoundField During GridView OnRowDataBound

March 6, 2009

Got a new project on a VB.NET app. One page has a GridView using asp:BoundField controls with one of them bound to a Date field. The Date might contain ’01/01/0001′ so I decided to display it as blank in that situtation.

Crunging The Confounded BoundField

I decided to handle the OnRowDataBound event which gives me access to the Row in GridViewRowEventArgs. But BoundField does not have a Control ID, so how to access the BoundField control from the Row…not possible to use Row.FindControl without a Control ID.

So what you do is access the Row’s TableCell collection giving the index of the GridView column you are interested in viz: e.Row.Cells[gridViewColumnIndex].Text

Here’s an example:

protected StudentGrid_RowDataBound(object sender, GridViewRowEventArgs e)
const DODGY_DATE_COLUMN = 3; — Date column is in 4th column of GridView
if (e.Row.RowType == DataRowControlType.DataRow)
— “Dodgy_Date” is the DataField property for the BoundField
Date dateVal = e.Row.DataItem(“Dodgy_Date”) as Date;
if (dateVal.Year == 1)
— Format ’01/01/0001′ as blank
e.Row.Cells[DODGY_DATE_COLUMN].Text = string.Empty;
— Got a real date. Format it as short date.
e.Row.Cells[DODGY_DATE_COLUMN].Text = String.Format(“{0:d}”, dateVal)

Here’s a further example from MSDN