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

Posted by Peter Kellner on May 24, 2006 · 4 mins read

(AKA, the DataFormatString="{0:M-dd-yyyy}" Problem)

 

A very common desire is to set a column of a GridView to display just the month, day and year of a DateTime type. The problem is the by default, the HtmlEncode property of the BoundField attribute ( <asp:BoundField ...) is set to True. The reason for this (as pointed out in the documentation of this attribute) is that this helps prevent cross-site scripting attacks and malicious content from being displayed. Microsoft recommends that the HtmlEncode attribute be enabled whenever possible.

[wp_ad_camp_1]

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

Good luck with your coding and hopefully, this will be one nasty you can put behind you.