Wednesday, 21 September 2011

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

(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.

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.

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

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>
  <asp headertext="CreationDate" dataformatstring="{0:M-dd-yyyy}" 
       datafield="CreationDate" :BoundField HtmlEncode="false" />

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>
  <asp headertext="CreationDate" :TemplateField>
    <asp id="Label1" runat="server" Label.Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'>
    <asp id="Label1" runat="server" Label.Text='<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'>;

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

Output of all three scenarios

<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#336666"BorderStyle="Double" BorderWidth="3px" CellPadding="4" AutoGenerateColumns="false"GridLines="Horizontal">           
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
                <asp:TemplateField HeaderText="Date" >
                        <asp:Label ID="Date" runat="server" Text='<%# Convert.ToDateTime(Eval("BookingDate")).ToString("dd/yyyy") %>'>asp:Label>