A date time picker is an easy and effective way of enabling a C# Windows application user to select a date. It appears on the form as a ComboBox containing a date but instead of the user seeing a drop-down list when they click on it they will see an interactive calendar.
The great thing for a C# programmer is that it can be created with the minimum of effort (for more information on how to create the date time picker read How to Add and Customize a C# Date Time Picker ). However, a C# programmer can do more than add a default date time picker: they can also:
- set the date for the date time picker
- limit the available dates for the date time picker
- add functionality to the date time picker
And, of course, this can all be done with some simple C# code.
Setting the Date in a Date Time Picker with C#
The C# programmer can alter the date shown in the date time by updating the object's "Value" property. They can specifically set the date (for example to April 27, 2009):
Or they can use a relative date (for example by adding 7 days to the current date):
In this way the programmer can set the date to anything they require. Of course, the user can change this date manually.
Limiting the Dates in a Date Time Picker with C#
The programmer can set the date held by the date time picker by using code (as shownabove) and the application user can select any date manually by using the interactive calendar. However, the programmer can limit the dates that may be selected by the user. Setting either of two of the DateTimePicker object’s properties does this:
- MinDate - the minimum date available to the user
- MaxDate - the maximum date available to the user
The programmer can set these in the same way as the date time picker's value, for example:
or:
If the form is compiled now then the user will only be able to select dates within the bounds set by the programmer.
Adding Functionality to a Date Time Picker with C#
As well as using code to customize how the DateTimePicker object responds to the user, the programmer can add bespoke C# code that will extend the functionality of the date time picker. They do this by adding a new C# event handler:
In this example a function (datePicker_ValueChanged) will be run whenever the user changes the value stored by the date time picker. The function called can be something like:
Now the user will be informed whenever they change the date in the date time picker.
Summary
Once a C# programmer has added a Date Time Picker (and for that read How to Add and Customize a C# Date Time Picker) then they can:
- set the date contained by the DateTimePicker object
- limit the minimum and maximum dates available to the application's user
- add further functionality to the date time picker by creating a new event handler
In this way the C# programmer can easily provide an application with a set range of dates available to the user, and they can create their own extension to the default functionality of the date time picker.