Tuesday, July 24, 2012

Quickly Formatting the date in an ASP.NET Gridview

I have recently been dealing with GridViews quite a bit, and one of the things that annoyed me was the way you had to format a date.

You are normally forced to create a function in your code-behind page, and pass the date to it - Which is annoying if you only ever need to format a single date on the page. Something like the following:


<asp:TemplateField HeaderText="Date Header Here">
public object FormatDate(object input)
   string stringObject = input.ToString();
   DateTime dttm = DateTime.Parse(stringObject);
   return dttm.ToString("dd-MMM-yyyy");

This was rather annoying, as it seemed like a very roundabout way to do something seemingly small. After messing around a bit, I found a nice compact way to do it in the GridView itself!

<asp:TemplateField HeaderText="Date Header Here">

Win! \o/

On an unrelated note, getting decently formatted ASP.NET / C# code in blogspot is a nightmare >_>

No comments :

Post a Comment