Reputation: 1218
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.
Upvotes: 7
Views: 73969
Reputation: 1
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;
Upvotes: 0
Reputation: 1
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();
}
Upvotes: 0
Reputation: 229
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}"
Upvotes: 1
Reputation: 13293
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.
Upvotes: 8
Reputation: 15794
You need to put that code after the InitializeComponent()
call is made. There is no instance of myDateTimePicker
until that point.
Upvotes: 9