Stefan Pienaar
I would love to change the world, but they won't give me the source code

How to bind a DateTime value to a GridView

October 8, 2008 10:36 by stefanpienaar

Binding a datetime value is just as straight forward as binding any other data type to your grid, here is a quick reference however on how to properly format it:

When binding to a BoundField:

<asp:BoundField HeaderText="Date Finalised" 
                HtmlEncode="false" 
                DataField="DateAgreementCompleted" 
                DataFormatString="{0:yyyy/MM/dd}" />

 

The only thing to note here is the DataFormatString and the HtmlEncode property. The DataFormatString works in exactly the same way you would format a datetime when using .ToString (here's a quick reference on string formatting in c#) and the HtmlEncode ensures that the data is displayed properly and not encoded by asp.net.

When binding to a TemplateField:

<asp:TemplateField HeaderText="Date Finalised">
    <ItemTemplate>
        <asp:Label ID="lblDate" runat="server" 
            Text='<%# Bind("DateAgreementCompleted", "{0:yyyy/MM/dd}") %>' />
    </ItemTemplate>
</asp:TemplateField>
Here you can see that we use the Bind function as we normally would but we included a second parameter to the function ("{0:yyyy/MM/dd}")
Categories: .net
Actions: E-mail | Permalink | Comments (0)