Format BoundField During GridView OnRowDataBound

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;
}
else
{
— 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

Advertisements

Tags: ,

One Response to “Format BoundField During GridView OnRowDataBound”

  1. development ~ notes on ASP.Net GridView « littledamien Says:

    […] An Example […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: