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>




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: