Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

July 14, 2009

Dates: Binding to Month Names

Visual Studio comes with DateTimePicker and MonthCalendar controls that provide a standard looking calendar for the user to pick a date. But there are times when these controls don’t provide the features you need.

For example, say you want to ask the user for the month and year that their credit card expires. Or you want to ask for a birth date and don’t want the user to have to scroll back to 1932. Or better yet, don’t need to know the year (not that I refuse to admit my birth year <G>.)

There is an easy way to achieve this.

The code is first shown in both VB and C#. It is then described in detail below.

In C#:

string[] MonthNames=
               CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
comboBox1.DataSource = MonthNames;

In VB:

Dim MonthNames As String() =  _
               CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
ComboBox1.DataSource = MonthNames

This code gets the month names based on the current culture. This ensures that you get the correct localized names. You can then bind the array to a ComboBox or ListBox.

NOTE: In both cases, be sure to set a reference and import System.Globalization.

When looking at the list from the US (and most countries), there is a problem. There appears to be room for 13 values in the list. This is for those countries that have 13 months, such as Ethiopia.

So for most countries, there is a blank entry at the bottom of the list when it is bound. There are numerous ways of removing the empty entry. Even though it might not be the most performant, I like lambda expressions, so here is one way to remove the empty entry.

In C#:

comboBox1.DataSource = 
     MonthNames.Where(m => !string.IsNullOrEmpty(m)).ToList();

In VB:

ComboBox1.DataSource = _
    MonthNames.Where(Function(m) Not String.IsNullOrEmpty(m)).ToList()

Enjoy!

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