C# 如何在 DateTimePicker 中设置当前时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11784362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:15:22  来源:igfitidea点击:

How to set the current time in a DateTimePicker

c#winformsdatetimepicker

提问by georgeliatsos

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

我正在尝试将当前时间设置为 DateTimePicker(带格式时间),例如

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.

谢谢。

采纳答案by code4life

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

您需要在InitializeComponent()调用后放置该代码。在myDateTimePicker那之前没有实例。

回答by phadaphunk

Declare your DateTimePickerand try it.

声明DateTimePicker并尝试一下。

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

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 DateTimePickergets initialized.

就像有人指出的那样,把你的代码放在你的代码之前,InitializeComponent()因为它在你DateTimePicker被初始化的那部分。

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

1 - 删除您的控制
2 - 重新添加它。
3 - 注意你把代码放在哪里。

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

在那之后应该可以工作,因为您在代码部分做得对。

回答by Bianca Kalman

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

如果您使用 WPF,而不是 WinForms,请添加以下参考:

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

Then in XAML DatePicker's code add:

然后在 XAML DatePicker 的代码中添加:

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