YCN
YCN

Reputation: 677

c# .Net DateTimePicker problem

this is what I am doing,

//this doesnt set the datetimepicker value to the set value 
class{
   constructor
   {
      InitializeComponent(); // -> this initializes all the form components

      DateTimePicker.Value = System.DateTime.Now.AddDays(30); //->trying to set the date time picker value to a date one month from now.

   }
}

//but this does set the date to the desired value..
class{
   constructor
   {
      InitializeComponent(); // -> this initializes all the form components

   }

   form_onLoad() //->on form load event
   {
     DateTimePicker.Value = System.DateTime.Now.AddDays(30);
   }
}

Can someone please explain whats the difference and why it doesnt change date with previous method? and why it sets with the latter method?

Upvotes: 1

Views: 771

Answers (2)

Johnny
Johnny

Reputation: 1575

DateTimePicker is a property of your form. You can not set any value of any property of form before it loads. So your 1st one doesn't work and the 2nd one does.

Upvotes: 1

Chris Laplante
Chris Laplante

Reputation: 29668

The first time you use this line:

DateTimePicker.Value = System.DateTime.Now.AddDays(30);

is before the form loads, in the form constructor. When the form actually loads, the value is reset. You can't manipulate controls in the instantiation code of the container.

Upvotes: 2

Related Questions