Have you ever wanted to bind a combo box to a list of month names and dates? There are a lot of different ways to do this and some are better than others. Here are the most common methods that I have seen over the years:
- Hardcode the month names in a combo. Nothing wrong with this, its not like they will change.
- Generated a Datatable and inserted rows into the table just for the purpose of binding. Again, not a bad way to go but not very elegant.
- Created a stored procedure to return the list of month names which then populated a Datatable. This method makes me cringe! A waste of a stored procedure and a round trip to SQL Server for no reason.
About a year ago, I ran into option #3 while I was reviewing someone's code. So I thought I was pretty creative when I came up with this code to populate a combo box with the month names:
1: public Form1() {
2: InitializeComponent();
3:
4: comboBox1.DataSource = new BindingSource(GetMonths(), null);
5: comboBox1.DisplayMember = "Value";
6: comboBox1.ValueMember = "Key";
7: }
8:
9: private Dictionary<int,string> GetMonths() {
10: Dictionary<int, string> results = new Dictionary<int, string>();
11: results.Add(0, "(Select One)");
12:
13: DateTime now = System.DateTime.Now;
14:
15: for (int i = 1; i <= 12; i++) {
16: DateTime myDate = new DateTime(2000,i,1);
17: results.Add(myDate.Month, myDate.ToString("MMMM"));
18: }
19:
20: return results;
21: }
This option is nice if you want to have a header row that gives the old "Select One" option and that has corresponding integer values for each month. As an alternative, I discovered this solution from Deborah Kurata's blog.
1: string[] MonthNames= CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
2: comboBox1.DataSource = MonthNames;
Pretty Slick! And if you want to add the extra header rows you can just add insert another string in the array before binding. Of course, you do not have any integer values mapped to the month names but you could use the SelectedIndex value of the combo box for this purpose.
Anyway, the moral of the story is that there is always opportunity to improve your code. Even though it compiles it does not mean its right. You have to get out there and look at other people's code. No matter how good of a programmer you are, you can always be better.