Tuesday, February 24, 2009

DataFormatString - displaying dates and times in a datagrid

A common requirement from clients is to have dates (DateTime values) in MM-DD-YYYY format in grids and other DataBound objects.

As we all know, the most common ways of doing this are by modifying the cell text in the DataBound event or by having a calculated column in your datasource.

There is a much easier way - using the DataFormatString property of BoundColumn. For example, the following code

<asp:DataGrid id=”DataGrid1” runat=”server” AutoGenerateColumns=False>
<Columns>
<asp:BoundColumn DataField=”Id” HeaderText=”Serial Number”></asp:BoundColumn>
<asp:BoundColumn DataFormatString=”” DataField=”IssueDate” HeaderText=”Issue Date”></asp:BoundColumn>
</Columns>
</asp:DataGrid>
Gives
Serial Number
Issue Date
1
8/25/2005 4:34:33 PM
2
9/4/2005 4:34:33 PM
3
9/24/2005 4:34:33 PM
4
10/4/2005 4:34:33 PM

And this code

<asp:DataGrid id=”DataGrid1” runat=”server” AutoGenerateColumns=False>
<Columns>
<asp:BoundColumn DataField=”Id” HeaderText=”Serial Number”></asp:BoundColumn>
<asp:BoundColumn DataFormatString=”{0:d}” DataField=”IssueDate” HeaderText=”Issue Date”></asp:BoundColumn>
</Columns>
</asp:DataGrid>
Gives
Serial Number
Issue Date
1
8/25/2005
2
9/4/2005
3
9/24/2005
4
10/4/2005

A one line change and doesn’t require compilation. A complete list of format strings can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDateTimeClassToStringTopic.asp

The string used in this case was "d"

No comments:

Post a Comment