I only found this little reference to it - you need to scroll down to find the relevant code sample underneath Community Content (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogeneratecolumns%28VS.80%29.aspx). I used a free code converter change it to C# but that code still needed work. The original converted code with original comments, and then mine added in below. This code is easily customized for a wide range of formatting output when your gridview is automatically generating columns.
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//use syntax to hide baddates
//maybe also do short date strings?
//http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogeneratecolumns%28VS.80%29.aspx
// Routine to display an unknown DateTime column
// as a short date at runtime
// By Ken Cox [Microsoft MVP]
// July 28/06
//
// Make sure this is a datarow being bound
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Create variables to hold values
DataRowView dtview = default(System.Data.DataRowView);
int intCounter = 0;
// Get the contents of the current row
// as a DataRowView
dtview = (DataRowView)e.Row.DataItem;
// Loop through the individual values in the
// DataRowView's ItemArray
for (intCounter = 0; intCounter <= dtview.Row.ItemArray.Length - 1; intCounter++)
{
// Check if the current value (item - Layla) is
// a System.DateTime type
if (dtview.Row[intCounter].GetType() == typeof(DateTime))
{
// If it is a DateTime, cast it as such
// into the variable
//Layla: cast item to DateTime
DateTime myNewDate = Convert.ToDateTime(dtview.Row[intCounter]);
//now test if that date is missing date, then hide it if so
if (myNewDate == myConstants.NOTCOMPLETE_DATETIME)
{
e.Row.Cells[intCounter].Text = "";
}
else
{
// Set the text of the current cell
// as the short date representation
// of the datetime
e.Row.Cells[intCounter].Text = myNewDate.ToShortDateString();
}
}
}
}
}
If you compare the original code you can see some small differences. Rather than create a DateTime variable holder to place the item into, I just create the variable IF NEEDED (if the item in the row being evaluated is of type DateTime) and populate it with the item cast as a DateTime. Very small, but I prefer that because I think it's easier to read/understand.
If anyone knows of any other ways to accomplish this - namely iterating through the items in a gridview row onrowdatabound, I'd love to compare it, so tell me about it in the comments!
No comments:
Post a Comment