4

我创建了一个非常简单的下拉框:

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

代码背后:

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

有没有办法让MonthDropDown(我的下拉框)显示月份的名称,而不是月份的数值。我想它可能是这样的

DateTimeFormatInfo.CurrentInfo.GetMonthName(MonthDropDown.SelectedIndex)?
4

2 回答 2

3

你是这个意思吗?

for (int n = 1; n <= 12; ++n)
    MonthDropDown.Items.Add(n, DateTimeFormatInfo.CurrentInfo.GetMonthName(n));

MonthDropDown.SelectedIndex = DateTime.Now.Month - 1; // note -1

请注意,这MonthDropDown.SelectedValue将是从一开始的值(1 = 一月),但MonthDropDown.SelectedIndex将从零开始(0 = 一月)。

于 2012-12-19T19:38:11.893 回答
3

这当然是特定于文化的,所以在CultureInfo类下查找它:

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

您可以将月份名称设置为 ListBox 中的值:

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

如果您仍希望所选作为索引,您也可以使用键/值:

MonthDropDown.DataSource = Enumerable.Range(1, 12)
    .Select(monthIndex=> 
        new ListItem(
            CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthIndex), 
            monthIndex.ToString()))
    .ToArray();
于 2012-12-19T19:39:17.030 回答