Dates: Binding to Day Numbers
Tue, Jul 14 2009 14:07
My prior post demonstrated how to bind to a list of month names. Once the user picks the desired month, you may want to provide a list of valid dates to pick a date in that month. For example: 1-30 for September and 1-31 for July.
You can accomplish this using a switch statement (Select Case in VB), but that hard-codes the dates, does not handle leap year, and does not support localization.
Another option is to use the culture specific calendar as shown below.
The code is first shown in both VB and C#. It is then described in detail below.
private List<int> GetListOfDays(int yearNumber , int monthNumber)
Calendar currentCalendar = CultureInfo.CurrentCulture.Calendar;
int numberOfDays =
return Enumerable.Range(1, numberOfDays).ToList();
Private Function GetListOfDays(ByVal yearNumber As Integer, _
ByVal monthNumber As Integer) As List(Of Integer)
Dim currentCalendar As Calendar = CultureInfo.CurrentCulture.Calendar
Dim numberOfDays As Integer = _
Return Enumerable.Range(1, numberOfDays).ToList()
This function first defines the calendar based on the current culture. It then uses the calendar’s GetDaysInMonth method to get the appropriate number of days in the month.
It then uses the Range method of Enumerable to build a list of numbers from 1 to the number of days in the month and returns it as a list of integers.
This method is called as follows:
comboBox1.DataSource = GetListOfDays(2009, 2);
ComboBox1.DataSource = GetListOfDays(2009, 2)