View Full Version : How do you set a DateTimePicker back to todays date in c#?

10-17-2008, 07:27 PM
I've tried all that i can think of to reset the date time picker back to today's date and nothing has worked.

I have got a clear button and wish to reset the date time picker back to todays date

Here is the code that i have so far:

private void btnClear_Click(object sender, EventArgs e)
if (dtpDate1.Value > dtpDate1.MinDate)
dtpDate1Value = DateTime.Today;
if (dtpDate2.Value > dtpDate2.MinDate)
dtpDate2.Value = DateTime.Today;

Additional Details

I'm using Microsoft Visual Studio 2005

I tried
dptDate1.Value = DateTime.Today;
but it gave me an error message saying that "Value does not fall within expected range"

10-17-2008, 07:51 PM
I don't have a c# development environment setup here at work but have you tried Date.Now?

Some sleuthing found this example on msdn

The following code example demonstrates how use the Value property to retrieve the current date value. First, the example displays the Value property. The example then increments the Value property by one day and displays the property value again.

// Create a new DateTimePicker
DateTimePicker dateTimePicker1 = new DateTimePicker();
Controls.AddRange(new Control[] {dateTimePicker1});

dateTimePicker1.Value = DateTime.Now.AddDays(1);
It's not exactly what you want as it gets the current date and adds 1 day to it, but it leads me to believe that you might be able to just use DateTime.Now instead.

I found this example here: http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

EDIT: The DateTimePicker also has properties for MinDate and MaxDate that can be set. Is it possible that you the min and max range such that today's date doesn't fall in the range? Based on the error this seems like it might be a possible reason.

// Create a new DateTimePicker control and initialize it.
DateTimePicker dateTimePicker1 = new DateTimePicker();

// Set the MinDate and MaxDate.
dateTimePicker1.MinDate = new DateTime(1985, 6, 20);
dateTimePicker1.MaxDate = DateTime.Today;

// Set the CustomFormat string.
dateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd";
dateTimePicker1.Format = DateTimePickerFormat.Custom;

// Show the CheckBox and display the control as an up-down control.
dateTimePicker1.ShowCheckBox = true;
dateTimePicker1.ShowUpDown = true;
This example is from: http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.mindate(VS.85).aspx

07-18-2010, 10:41 AM
U need Just one line :cool: :cool:

dateTimePicker1.Value = System.DateTime.Now;