How to set the current time in a DateTimePicker

63,659

Solution 1

You need to put that code after the InitializeComponent() call is made. There is no instance of myDateTimePicker until that point.

Solution 2

Declare your DateTimePicker and try it.

DateTimePicker myPicker = new DateTimePicker;
myPicker.Value = DateTime.Now;

Like someone pointed out, put your code before the InitializeComponent() since it's in that part that your DateTimePicker gets initialized.

1 - Delete you control
2 - Re-add it.
3 - Watch where you put your code.

Should work after that since your doing it right on the code part.

Solution 3

If you use WPF, not WinForms, add this reference:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Then in XAML DatePicker's code add:

SelectedDate="{x:Static sys:DateTime.Now}"
Share:
63,659
georgeliatsos
Author by

georgeliatsos

Updated on July 09, 2022

Comments

  • georgeliatsos
    georgeliatsos almost 2 years

    I am trying to set the current time to a DateTimePicker (with Format Time) like

    this.myDateTimePicker.Value = DateTime.Now;
    

    but when executing my code I am getting an exception

    Object reference not set to an instance of an object    
    

    What I am doing wrong?

    Thanks.