How to set the current time in a DateTimePicker

Viewed 66461

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.

5 Answers

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}"

set this code in your 'form1_Load' event

DateTimePicker dtpPurDate = new DateTimePicker;
dtpPurDate.Text = DateTime.Now.ToShortTimeString();

private void form1_Load(object sender, EventArgs e)
{
     DateTimePicker dtpPurDate = new DateTimePicker;
     dtpPurDate.Text = DateTime.Now.ToShortTimeString();
}

If you working with Forms just add DateTimePicker object from Toolbox , and first call InitializeComponent() Or just create new instance in your code

 this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();

Only after creating instance of an DateTimePicker you can use it:

this.dateTimePicker1 .Value = DateTime.Now;
Related