Henry Henry - 2 months ago 39
C# Question

Binding TimeSpan to DateTime control (Entity Framework)

I am working with C# Winform and Entity Framework,

My question is, Is there a way to bind a TimeSpan property to DateTime control?

I have a

DataGridView
which is
DataBounded
to a entity framework
DbSet
.
DbSet
has a
TimeSpan
property which I binded to a
DateTime
control but displayed as
Time
only. my Binding is modeled here: Entity Framework - (master detail) how to update Details which on a separate form from Master

Upon execution of the program, no error displayed on build but time is not displayed on the control as well as saving, time is not saved too. :(

Answer

TimeSpan and DateTime are not interchangeable. I believe the simplest solution is create a control derived from DateTimePicker that exposes a TimeSpan property and bind to that.

public class TimePicker : DateTimePicker, System.ComponentModel.INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public TimePicker()
        : base()
    {
        this.Format = DateTimePickerFormat.Time;
    }

    public TimeSpan Time
    {
        get
        {
            return this.Value.TimeOfDay;
        }
        set
        {
            this.Value = DateTime.Today.Add(value);
        }
    }

    protected override void OnValueChanged(EventArgs eventargs)
    {
        base.OnValueChanged(eventargs);
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("Time"));
    }
}

Then you can bind to it something like this:

timePicker1.DataBindings.Add("Time", bindingSource1, "TS", true, DataSourceUpdateMode.OnPropertyChanged);
Comments