Henry Henry - 1 year ago 250
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

which is
to a entity framework
has a
property which I binded to a
control but displayed as
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 Source

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
            return this.Value.TimeOfDay;
            this.Value = DateTime.Today.Add(value);

    protected override void OnValueChanged(EventArgs 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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download