Is it possible to format a date column of a datatable?

The smartest thing to do would be to make sure your DataTable is typed, and this column is of type DateTime. Then when you go to actually print the values to the screen, you can set the format at that point without mucking with the underlying data.

If that’s not feasible, here’s an extension method I use often:

public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
    foreach(DataRow row in column.Table.Rows)
    {
        row[column] = conversion(row[column]);
    }
}

You could use in your situation like:

myTable.Columns["DateOfOrder"].Convert(
    val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));

It only works on untyped DataTables (e.g. the column type needs to be object, or possibly string).

Leave a Comment