Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to code up a Month and Year drop down list for ASP.NET?

I have an internal application that I needs to have a drop down list for two date type elements: Month and Year. These values are not in a database or other repository of information.

I know I could just setup a list with the values I need by adding them to a dictionary like object (I need to correlate the Month to the numerical representation, January => 01):

var months = new Dictionary<String,String>();
months.Add("01", "January");
...

The drop down list for the year will be a bit easier as I can just choose a starting year and iterate up to the current or current+1 year in a generic list.

Is there a better way to handle these data elements? Something built in, or a good design pattern that I should be implementing?

like image 327
Astra Avatar asked May 01 '09 17:05

Astra


3 Answers

Somebody has asked that they wanted a numeric representation of the months. Here's my codebehind:

// DOB MONTHS
dob_month1.Items.Insert(0, new ListItem("Select", "")); 
var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
for (int i = 1; i < months.Length; i++)
{
    dob_month1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}

It's basically the same as the answer code with minor adjustments.

Result:

enter image description here

like image 132
Dennis R Avatar answered Jan 01 '23 08:01

Dennis R


You could use this to get a list of all the Month names and loop through it.

CultureInfo.CurrentCulture.DateTimeFormat.MonthNames

You can use it like this...using the index of the Month as the value for your dropdown

var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
for (int i = 0; i < months.Length; i++)
{
     ddl.Items.Add(new ListItem(months[i], i.ToString()));
}
like image 45
Jab Avatar answered Jan 01 '23 08:01

Jab


Extending @Jesse Brown's answer...

With a using System.Globalization directive, I have the following code:

for (int x = 0; x < 12; x++)
{
    cboMonth.Items.Add
    (
       (x+1).ToString("00") 
       + " " 
       + CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.GetValue(x)
     );
}

This produces a dropdown list that looks like:

01 January 02 February 03 March ... 12 December

A further refinement might be to make the displayed month the current month by adding:

cboMonth.Text = DateTime.Now.Month.ToString("00") 
   + " " 
   + CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.GetValue(DateTime.Now.Month);

After the for loop.

like image 39
Cyberherbalist Avatar answered Jan 01 '23 09:01

Cyberherbalist