How To Set a Date Format In GridView Using ASP.NET (Using HtmlEncode Property)

The problem is that if this field is enabled, you can not pass format information to the boundfield control. That is, if you try the following code, you will not get the desired result.

<columns> <asp headertext="CreationDate" dataformatstring="{0:M-dd-yyyy}" datafield="CreationDate" :BoundField /> </columns> </asp>

You have two choices to make this work as you would expect. The first choice is to simply set HtmlEncode to false as follows:

<asp id="GridView1" runat="server" :GridView> <columns> <asp headertext="CreationDate" dataformatstring="{0:M-dd-yyyy}" datafield="CreationDate" :BoundField HtmlEncode="false" /> </columns>

The second choice is to make the column a template and simply set the format string directly in the Label or Text Fields as follows.

<asp id="GridView3" runat="server" :GridView> <columns> <asp headertext="CreationDate" :TemplateField> <edititemtemplate> <asp id="Label1" runat="server" Label.Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'> </asp> </edititemtemplate> <itemtemplate> <asp id="Label1" runat="server" Label.Text='<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'>; </asp> </itemtemplate> </asp> </columns> </asp>

Below is a screen shot of what the three scenarios discussed above look like.

Output of all three scenarios

This entry was posted in 4-Coding and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.