Get the month name displayed in a very simple drop down list

I created a very simple dropdownbox:

<asp:DropDownList ID="MonthDropDown" runat="server" AutoPostBack="True"> </asp:DropDownList> 

Code for:

 MonthDropDown.DataSource = Enumerable.Range(1, 12); MonthDropDown.SelectedIndex = DateTime.Now.Month; MonthDropDown.DataBind(); 

Is there a way to get MonthDropDown (my dropdownbox) to display the name of the month and not the numeric value of the month. I think it might be something like

 DateTimeFormatInfo.CurrentInfo.GetMonthName(MonthDropDown.SelectedIndex)? 
+4
source share
2 answers

Of course, it depends on the culture, so find it under the CultureInfo class:

 string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthIndex); 

You can set month names as values ​​in a ListBox:

 MonthDropDown.DataSource = Enumerable.Range(1, 12) .Select(monthIndex => CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthIndex)) .ToArray(); 

You can also use keys / values ​​if you want the selected value to be an index:

 MonthDropDown.DataSource = Enumerable.Range(1, 12) .Select(monthIndex=> new ListItem( CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthIndex), monthIndex.ToString())) .ToArray(); 
+3
source

Is that what you mean?

 for (int n = 1; n <= 12; ++n) MonthDropDown.Items.Add(n, DateTimeFormatInfo.CurrentInfo.GetMonthName(n)); MonthDropDown.SelectedIndex = DateTime.Now.Month - 1; // note -1 

Note that MonthDropDown.SelectedValue will be a unidirectional value (1 = January), but MonthDropDown.SelectedIndex will be based on zero (0 = January).

+3
source

All Articles