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?
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:
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()));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With