1

I have an ASP.NET 3.5 application with a gridview in a page.

I want to format one of the columns as a datetime. I've tried:

<asp:BoundField DataField="StatusDate" HeaderText="as of" SortExpression="StatusDate" DataFormatString="{0:d}" />

The problem is no matter what I do, my formatting never changes. I've tried the other date formatting strings (general, sortable, longdate, the list goes on), but the format of this column never changes.

I don't think I'm doing anything wrong, but this is driving me nuts when I try to sort based on this column. Because the default is formatting the column as a string, it doesn't sort correctly when I sort by the column header.

Anyone seen this and have some kind of workaround? I've seen articles mentioning adding a custom sort method, but I'm trying to stick to out-of-the-box functionality if I can.

Tim
  • 4,051
  • 10
  • 36
  • 60

4 Answers4

2

I've actually had this issue a few times and have come up with the following solution. First off I place all of my data in a DataTable for storage.

Secondly, the column of which I need to format something specifically I also implicitly define the data type.

    DataTable table = new DataTable();
    table.Columns.Add("decimalNumber").DataType = System.Type.GetType("System.Decimal");
    table.Columns.Add("date").DataType = System.Type.GetType("System.DateTime");

Then when I call it in the GridView

    <asp:BoundField DataField="decimalNumber" DataFormatString="{0:C}" />
    <asp:BoundField DataField="date" DataFormatString="{0:dd/MM/yyyy}" />

And the results will look like this $0.00 & 19/11/2014. I hope this helps.

0

You cannot format as datetime from string.

However, You can use the following approach. Output is basically same as using BoundField.

<asp:TemplateField HeaderText="as of" SortExpression="StatusDate">
   <ItemTemplate>
      <asp:Literal ID="Literal1" runat="server" 
        Text='<%# string.Format("{0:d}",  Convert.ToDateTime(Eval("StatusDate"))) %>'>        
      </asp:Literal>
   </ItemTemplate>
</asp:TemplateField>
Win
  • 61,100
  • 13
  • 102
  • 181
0

The problem is that the datatype of your data/column is a string. Your DataFormatString property will only work on a datetime column. The solution to this problem can be found in this SO answer.

Formatting applied to boundfields in gridview is not working

Community
  • 1
  • 1
Stuart
  • 671
  • 7
  • 20
0

Because the data type of the source of that column is not datetime!