How to set current time in DateTimePicker

I am trying to set the current time to a DateTimePicker (with formatting time), e.g.

this.myDateTimePicker.Value = DateTime.Now; 

but when I execute my code I get an exception

 Object reference not set to an instance of an object 

What am I doing wrong?

Thanks.

+6
source share
3 answers

You need to put this code after calling InitializeComponent() . There is no instance of myDateTimePicker to this point.

+7
source

Declare your DateTimePicker and try.

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

As someone pointed out, put your code in front of InitializeComponent() , since it is in the part that your DateTimePicker initializes.

1 - Remove Management
2 - Re-add it.
3 - See where you put your code.

This should work after this, since you are doing it right on part of the code.

+5
source

If you are using WPF, not WinForms, add this link:

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

Then in the XAML DatePicker code add:

 SelectedDate="{x:Static sys:DateTime.Now}" 
-1
source

Source: https://habr.com/ru/post/921986/


All Articles