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?
Extending @Jesse Brown's answer...
With a using System.Globalization directive, I have the following code:
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:
After the for loop.
Here is my solution, which is very similar to @jesse-brown's solution (the accepted answer)
VB.NET:
In a global functions class:
On the ASPX page:
This implementation is in VB.NET because that happens to be what this webapp is using (legacy), however thank you very much for the examples in C# (my preferred language), I'm posting the VB.NET here to help the VB.NET community as well.
For ASP.NET MVC this is what I'm doing.
Note I prefer to use a codebehind for things like this - its still part of the view and there's nothing wrong with the view constructing a SelectList.
PaymentControl.ascx
PaymentControl.ascx.cs
You could use this to get a list of all the Month names and loop through it.
You can use it like this...using the index of the Month as the value for your dropdown
You can try this... Ref Here:
http://allinworld99.blogspot.com/2015/01/bind-monthsyear-dropdownlist-c-aspnet.html