Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

July 14, 2009

Dates: Binding to Day Numbers

Filed under: C#,Data Binding,VB.NET,WinForms @ 4:07 pm

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.

In C#:

private List<int> GetListOfDays(int yearNumber , int monthNumber)
{
    Calendar currentCalendar  = CultureInfo.CurrentCulture.Calendar;
    int numberOfDays  =
              currentCalendar.GetDaysInMonth(yearNumber, monthNumber);
    return Enumerable.Range(1, numberOfDays).ToList();
}

In VB:

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 = _
               currentCalendar.GetDaysInMonth(yearNumber, monthNumber)
  Return Enumerable.Range(1, numberOfDays).ToList()
End Function

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:

In C#:

comboBox1.DataSource = GetListOfDays(2009, 2);

In VB:

ComboBox1.DataSource = GetListOfDays(2009, 2)

Enjoy!

1 Comment

  1.   Ciro — November 20, 2009 @ 8:51 am    Reply

    Deborah,

    This tip is very cool!

    Thank you to share with us.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2021 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs