Format Date Time using BoundColumn / ButtonColumn in DataGrid

A very common desire is to set a column of a DataGrid/GridView to display just the month, day and year (or other custom formats) for a dateTime field.

Below is an example for the same,

The first column with header 'DateTime 1' is a BoundColumn which uses DataFormatString="{0:yyyy.MM.dd}". This will format a date time string of 28-10-2011 12:52:00 to 2011.10.28.

The same can be used with ButtonColumn, as shown here the date time string of 28-10-2011 12:52:00 is converted to a format of 2011.10.28 12:52

<asp:DataGrid ID="abc" CssClass="default" DataKeyField="Id"  
OnItemCommand="myCommand" AutoGenerateColumns="false" Runat="Server" > 

<Columns> 

<asp:BoundColumn HeaderText="DateTime 1" DataField="dt1"  
DataFormatString="{0:yyyy.MM.dd}"  /> 

<asp:ButtonColumn HeaderText="DateTime 2" 
 DataTextField="dt2" DataTextFormatString="{0:yyyy.MM.dd hh:mm}"  
ButtonType="LinkButton" CommandName="Select" runat="server"/> 

</Columns> 

</asp:DataGrid>

0 comments:

Post a Comment