April 13, 2009

Change DateFormat In an ASP.NET GridView




While displaying dates in the GridView, a very common requirement is to display the date format in a user friendly manner. By default, the HTMLEncode property of a BoundField is set to True, which makes it difficult to format the date.

Note: HTMLEncode=True helps prevent cross-site scripting attacks.

In order to display the date in a user friendly date format, use the following method to turn off the HTMLEncode and use :


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:BoundField DataField="SomeDate" DataFormatString="{0:MM-dd-yyyy}"


HtmlEncode="false" HeaderText="SomeDate" />


...


</Columns>


</asp:GridView>




If you do not want to do it this way, the other way is to use a Template Field as shown below


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:TemplateField HeaderText="SomeDate" >


<EditItemTemplate>


<asp:Label ID="lblDate" runat="server" Text='<%# Eval("SomeDate", "{0:MM-dd-yyyy}") %>'


</asp:Label>


</EditItemTemplate>




...


</Columns>


</asp:GridView>




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Change DateFormat In an ASP.NET GridView"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions