Mike
Mike

Reputation:

How can I set a DateTimePicker control to a specific date?

How can I set a DateTimePicker control to a specific date (yesterday's date) in C# .NET 2.0?

Upvotes: 46

Views: 198080

Answers (9)

Sujeet Jayram
Sujeet Jayram

Reputation:

dateTimePicker1.Value = DateTime.Today();

Upvotes: 1

Lê Quang Duy
Lê Quang Duy

Reputation: 787

If you want to set a date, DateTimePicker.Value is a DateTime object.

DateTimePicker.Value = new DateTime(2012,05,28);

This is the constructor of DateTime:

new DateTime(int year,int month,int date);

My Visual is 2012

Upvotes: 25

Traderhut Games
Traderhut Games

Reputation: 1292

FYI: If you are setting the value, and not seeing anything - you might check to see if you have a 'CustomFormat' set - I just hit this and it was set to ' ' for the 1/1/1900 value (our 'not set' value) and set to MM/dd/yyyy if not.

Upvotes: 1

Nirav Raval
Nirav Raval

Reputation: 121

Also, we can assign the Value to the Control in Designer Class (i.e. FormName.Designer.cs).

DateTimePicker1.Value = DateTime.Now;

This way you always get Current Date...

Upvotes: 1

Kakha Middle Or
Kakha Middle Or

Reputation: 164

Can't figure out why, but in some circumstances if you have bound DataTimePicker and BindingSource contol is postioned to a new record, setting to Value property doesn't affect to bound field, so when you try to commit changes via EndEdit() method of BindingSource, you receive Null value doesn't allowed error. I managed this problem setting direct DataRow field.

Upvotes: 4

lc.
lc.

Reputation: 116538

Use the Value property.

MyDateTimePicker.Value = DateTime.Today.AddDays(-1);

DateTime.Today holds today's date, from which you can subtract 1 day (add -1 days) to become yesterday.

DateTime.Now, on the other hand, contains time information as well. DateTime.Now.AddDays(-1) will return this time one day ago.

Upvotes: 2

Rowland Shaw
Rowland Shaw

Reputation: 38128

Just need to set the value property in a convenient place (such as InitializeComponent()):

    dateTimePicker1.Value = DateTime.Today.AddDays(-1);

Upvotes: 81

Sessiz Saat
Sessiz Saat

Reputation: 1099

You can set the "value" property

dateTimePicker1.Value = DateTime.Today;

Upvotes: 9

user6212
user6212

Reputation:

This oughta do it.

DateTimePicker1.Value = DateTime.Now.AddDays(-1).Date;

Upvotes: 2

Related Questions