Tuesday, July 24, 2012

Quickly Formatting the date in an ASP.NET Gridview

Console.WriteLine("Woop!");
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:

Page.aspx

<asp:TemplateField HeaderText="Date Header Here">
   <ItemTemplate>
      <%#FormatDate(Eval("SQLDateValue"))%>
   </ItemTemplate>
</asp:TemplateField>
Page.aspx.cs
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">
   <ItemTemplate>
      <%#DateTime.Parse(Eval("DateReceived").ToString()).ToString("dd-MMM-yyyy")%>
   </ItemTemplate>
</asp:TemplateField>

Win! \o/

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

Friday, July 20, 2012

Kitten Attack!

Since I really need to start posting something here (I always plan to, but it gets delayed), a little something comical to fill the space :D