09 March 2009

Formatting date in ASP.NET gridview

One of our requirements while working with Gridview was formatting a datetime column to display only the date. One of the most important properties to be considered, along with the DataFormatString property, is the HTMLEncode property.

By default, the value for HTMLEncode is set to True. This is done to prevent cross-site scripting attacks and malicious content from being displayed. As a result, format information cannot be passed to the BoundField column.


<asp id="GridView1" runat="server">
<columns>
<asp :BoundField DataField="ExpiryDate"
DataFormatString="{0:MM-dd-yyyy}"
HeaderText="Expiry Date" />
</columns>
</asp>


The HTML code shown below will solve this issue.

<asp id="GridView1" runat="server">
<columns>
<asp :BoundField DataField="ExpiryDate"
DataFormatString="{0:MM-dd-yyyy}"
HtmlEncode="False"
HeaderText="Expiry Date" />
</columns>
</asp>


Hope this saves some valuable time for a few developers.

No comments:

Post a Comment