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>







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: