3

I have a list of Months displayed in a drop down. On selecting a particular month I would like to display the number of the month in a text box.

For example if I select January I would like to display it as 01, likewise for the others.

This is the sample code I have written:

string monthName = "january";
int i = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month;
David Clarke
  • 12,888
  • 9
  • 86
  • 116
Vivekh
  • 4,141
  • 11
  • 57
  • 102

4 Answers4

14

Use this code to convert the selected Month Name into a Month Number

DateTime.ParseExact(monthName, "MMMM", CultureInfo.InvariantCulture).Month

Need String Padding?

PadleftMonthNumberString.PadLeft(2, "0")

References

Sample Console Application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string mnthname = "january";
            int i = DateTime.ParseExact(mnthname, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month;
            Console.WriteLine(i.ToString());
            Console.ReadLine();
        }
    }
}
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
3

Just trying to improvise(?) on hamlin11's answer, you can bypass the parse code by using the dropdown's selectedindex+1

Schu
  • 1,124
  • 3
  • 11
  • 23
3

Here's an alternative that doesn't require any parsing or using the index of the drop down.

Create a list of month value to month text and then use this to create a dictionary to map the text to the value. Like this:

var months =
    from m in Enumerable.Range(1, 12)
    select new
    {
        Value = m,
        Text = (new DateTime(2011, m, 1)).ToString("MMMM"),
    };

var list = months.Select(m => m.Text).ToArray();
var map = months.ToDictionary(m => m.Text, m => m.Value);

Now the drop down can be populated from list and any value selected can be converted back to the value using map.

var month = map["January"];

This generates the text rather than parsing it so it should work for any culture.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

Using the index of the drop down list is a good option. You can also bind a dictionary to a drop down list. Creating a dictionary containing month names for the current culture:

var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.Select ((m, i) =>
    new {
        Key = string.Format("{0,2}", i + 1),
        Value =  m,
    });

With databinding:

ddl.DataSource = months;
ddl.DataTextField = "Value";
ddl.DataValueField = "Key";
ddl.DataBind();
David Clarke
  • 12,888
  • 9
  • 86
  • 116