Setting DatePicker Value

泄露秘密 提交于 2020-06-11 16:40:28

问题


I currently have a program that takes the value from a datePicker and have the date saved as a string. I only needed the date not the time so i used the following code to save the date value:

DateTime StartDate;
String inMyString;
savedDate = datePicker1.SelectedDate.Value.Date;
inMyString =   savedDate.Date.ToShortDateString()

I have the inMyString pushedBack into my list and now i want to place it back into the datePicker.

On MSDN is shows me the following example to set the date.

dateTimePicker1.Value = new DateTime(2001, 10, 20);

the problem is that having .Value after my date picker is not an option (it doesn't show in Intellisense.)

I have also tried

datePicker1.SelectedDate.Value= new DateTime(inMyString)

and also converting the inMyString to type DateTime but it still does not work.

Any thoughts on how to do this?
Any Suggestions and comments are appreciated.

Thanks!


回答1:


Try this:

datePicker1.SelectedDate = new DateTime(2001, 10, 20);

If you need to take datetime from string:

datePicker1.SelectedDate = DateTime.Parse(inMyString);

Side note:

You can replace those 3 lines:

String inMyString;
savedDate = datePicker1.SelectedDate.Value.Date;
inMyString = savedDate.Date.ToShortDateString();

with one:

var inMyString = datePicker1.SelectedDate.Value.ToShortDateString();

Another side note: don't know if there is a reason to it, but you might consider storing datetime as dattime, not as a string.




回答2:


If you want to show today's date in WPF C#, use this method:

datePicker1.SelectedDate = DateTime.Today.AddDays(-1);


来源:https://stackoverflow.com/questions/6398418/setting-datepicker-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!