Vivekh
Vivekh

Reputation: 4259

How to display month number on selecting month name

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;

Upvotes: 3

Views: 24703

Answers (4)

Brian Webster
Brian Webster

Reputation: 30855

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();
        }
    }
}

Upvotes: 14

David Clarke
David Clarke

Reputation: 13256

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();

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117029

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.

Upvotes: 3

Schu
Schu

Reputation: 1164

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

Upvotes: 3

Related Questions