I have a DGV bound to a list of objects whose properties include a DateTime value. I'd like to display, and allow editing the Date and Time components in separate columns. How would I do this?
+1
A:
Here's how I'd do it.
Make your property that exposes the DateTime
(together) invisible in the DataGridView
.
Have two other properties, Date
and Time
and have these properties essentially link back to your DateTime
property.
Like this:
[Browsable(false)]
public DateTime DateTime { get; set; }
public DateTime Date
{
get { return this.DateTime.Date; }
set
{
TimeSpan time = this.Time;
this.DateTime = value.Date + time;
}
}
public TimeSpan Time
{
get { return this.DateTime.TimeOfDay; }
set
{
this.DateTime = this.Date + value;
}
}
Dan Tao
2010-09-01 13:40:54
If you're suggesting I change the bound object, I can't do so directly since it's coming from a 3rd Party API. I could write a wrapper class but that seems like a kludge.
Dan Neely
2010-09-01 13:43:52
@Dan Neely: Hmm, well if you're not in control of the class, then I'm afraid a wrapper class is going to be your only option if you want the `DataGridView` to take care of the data binding for you (at least as far as I know). Otherwise, I might recommend simply inserting your own two columns manually, handling the cell change events, checking whether the change occurs in one of those two columns, and updating the underlying object yourself. Maybe there's a more elegant way, but that's how I'd do it.
Dan Tao
2010-09-01 13:46:42