Have you ever wanted to display a datetime value in a gridview, with a specific format? It doesn't always work intuitively because the <asp:BoundField> uses HtmlEncoding by default to prevent cross site scripting ( as referenced here ), so DateTime formatting techniques using the "DataFormatString" attribute of the BoundField will not work. Fixing this is fairly straight forward thoug, all you need to do is either
1.) Turn off HtmlEncode for the BoundField
2.) Use <asp:TemplateField>
Here is an example using the technique to turn the HtmlEncoding off:
<asp:BoundField
DataField="EndDate"
HeaderText="End Date"
DataFormatString="{0:M-dd-yyyy}"
HtmlEncode="false" />
Here is an example using the <asp:TemplateField> method:
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<%# DateTime.Parse(Eval("EndDate").ToString()).ToShortDateString() %>
</ItemTemplate>
</asp:TemplateField>
Posted
Jan 10 2009, 08:37 PM
by
dacrowlah