Formatting Date Strings in ASP.NET Gridviews
- January 4th, 2010
- Posted in Software
- Write comment
I’m blogging about this as it is a constant speedbump I find myself crossing. We’ve been using TemplateFields in gridviews exclusively for a couple of years now since we’ve always found ourselves having to convert BoundFields to TemplateFields in order to get extra functionality that we need in most cases. There’s extra coding to do, but we only use what we need, and, thus, i’m assuming that it’s a little more efficient. I’ll reasearch the topic and include it in another blog.
If, in the item template, a label is used to display text, I’ve gone around-and-around, via trial and error, trying to display dates with the short date format. Today I stumbled upon a link that provides solutions for both BoundFields & labels inside of TemplateFields: http://www.codedigest.com/Articles/ASPNET/137_How_to_format_DateTime_in_GridView_BoundColumn_and_TemplateColumn.aspx
The solution for the label inside of the TemplateField, which I’m most concerned about here, is:
- Be sure to use Eval rather than Bind (I always use Bind–this was the ‘Gotcha!’) in the text property of the label
- in Eval, include the format string in the second parameter (i.e. Eval(”Field_Name”, “{0:d}”) )
That was a simple fix that took me 2 hours of trial and error to get nowhere before finally searching for a solution elsewhere!
No comments yet.