I am creating column in DataTable like :
headerTable.Columns.Add(VendInvoice.Date, typeof(???));
I dont know how can i add just a date column, I know how to add dat开发者_JAVA百科eTime column.
There is no type in the BCL that implements just a date with no time.
Even if there were, the DataColumn
class wouldn't support it. Here is the list of types you're allowed to use. For chronological data you have DateTime
and TimeSpan
- that's it.
What you can do, if you want to pass this DataTable
to callers who may not be aware of the desired date-only semantics, is attach an event handler to the DataTable
itself which resets the time of day:
private void DataTable_RowChanged(object sender, DataRowChangedEventArgs e)
{
if ((e.Action & DataRowAction.Add) != 0) ||
(e.Action & DataRowAction.Change) != 0))
{
DateTime dt = (DateTime)e.Row[DateColumn];
if (dt != dt.Date)
e.Row[DateColumn] = dt.Date;
}
}
// Later ...
dataTable.RowChanged += DataTable_RowChanged;
Note that the conditional logic is necessary to prevent infinite recursion in the event handler.
I really don't think I'd do this, to be perfectly honest. Instead I would just use the DateTime.Date
method when accessing the value in the column, as opposed to worrying about what happens when it's written. But if for some reason your domain rules don't allow you to take that approach, you can use the handler above.
精彩评论