Search code examples
c#winformsdatetimepicker

DateTimePicker's funny issues


I have some funny (?!?) issues with the DateTimePicker and hopefully someone can help me out. I have a form with a DateTimePicker on it and I want to bind it to a property of a custom class. DateTimePicker has a custom format set to dd.MM.yyyy HH:mm:ss. Here is what I have tried and the troubles with those tries:

  • I made a binding to the Value property of DateTimePicker. The property of my custom class contains a valid date. When I run the app I get an ArgumentOutOfRangeException stating that "01.01.0001 00:00:00" is not a valid value for value and it should be between MinDate and MaxDate. (But I can't set neither DateTime.MaxValue nor DateTime.MinValue to the value property!)
  • I made a binding to the Text property of DateTimePicker. All is running well, but the seconds are always shown as "00". I can enter different values and they are reflected to the bound property of my custom class!

Any ideas?

Edit Here is the code snippet out of the designer file:

this.dateTimePickerTimestampFrom.CustomFormat = "dd.MM.yyyy HH:mm:ss";
this.dateTimePickerTimestampFrom.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSourceSelectLogEntries, "DateFrom", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.dateTimePickerTimestampFrom.Enabled = false;
this.dateTimePickerTimestampFrom.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.dateTimePickerTimestampFrom.Location = new System.Drawing.Point(81, 42);
this.dateTimePickerTimestampFrom.Name = "dateTimePickerTimestampFrom";
this.dateTimePickerTimestampFrom.Size = new System.Drawing.Size(147, 20);
this.dateTimePickerTimestampFrom.TabIndex = 3;

Edit 2 The bindingsource is a custom class containing a couple of properties. The values are valid at the moment the binding is set. I set it in the following code:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    // Exception is thrown at the following line.
    // controller is an instance of my custom class containing valid values.
    bindingSourceSelectLogEntries.DataSource = controller; 
}

Solution

  • I found out the solution by myself and I would like to tell, so others may not spend so much time on the same problem like I did.

    My design consists of a form and a controller (containing the data to present). In the form I wanted to do everything in the designer to minimize the code behind. So I had a binding source on the form, having an instance of my controller as DataSource. ReflectorPro helped me to find out, that the CurrencyManager was involved because the BindingSource was treated as a list. Therefore all values of all binded controls were set to null prior to get the values from the controller. DateTimePicker doesn't like null as a value for its Value property and throws the exception.

    Now I did the binding manually in code behind and everything works as I expected.