DateTimePicker Default value: How to avoid it?

Jhonny D. Cano -Leftware- picture Jhonny D. Cano -Leftware- · Sep 9, 2009 · Viewed 8.7k times · Source

Facts:

  • I have a TabControl with 2 Tabs, Each tab has 2 DateTimePicker.
  • In the Load event, I set the value of all the DTPs.
  • All DTPs have ShowCheckBoxes set on true AND Checked set on false.
  • When I Execute the program, The DTPs in first tab are OK, but when I check the DTPs on second tab, they show current time, not the time I set on the load event.

Why this happen? How can I avoid it?

Answer

GONeale picture GONeale · Nov 18, 2009

I found out what the problem was here.

The Value property only sets a new value if the DateTimePicker control is visible. Otherwise command is ignored.

Test case:

Doesn't work:

 this.picker = new DateTimePicker
        {
            Checked = false,
            Font = new System.Drawing.Font("Verdana", 9.75F),
            Format = System.Windows.Forms.DateTimePickerFormat.Time,
            Location = new System.Drawing.Point(5, 5),
            Name = "picker",
            ShowUpDown = true,
            Size = new System.Drawing.Size(120, 23),
            Visible = false
        };
        this.Controls.Add(this.picker);
        this.picker.Value = this.picker.Value.Date.AddHours(1);
        this.picker.Visible = true;

Works:

 this.picker = new DateTimePicker
        {
            Checked = false,
            Font = new System.Drawing.Font("Verdana", 9.75F),
            Format = System.Windows.Forms.DateTimePickerFormat.Time,
            Location = new System.Drawing.Point(5, 5),
            Name = "picker",
            ShowUpDown = true,
            Size = new System.Drawing.Size(120, 23),
            Visible = false
        };
        this.Controls.Add(this.picker);
        this.picker.Visible = true;
        this.picker.Value = this.picker.Value.Date.AddHours(1);

Doesn't appear to have anything to do with programatically adding the picker it seems.