使用月份名称填写下拉列表

时间:2015-03-07 22:12:58

标签: c# asp.net

我试图用月份名称填写下拉列表。但它一直给我一个FormatException。我使用类似的方法填写多年的下拉列表,但这并没有使用DateTime。

给出错误信息:

类型' System.FormatException'的例外情况发生在mscorlib.dll中但未在用户代码中处理

其他信息:De tekenreeks是niet als geldige DateTime herkend。

粗略翻译:字符序列不是有效的DateTime。

public void vulMaand()
    {
        for (int i = 0; i < 12; i++)
        {
            ListItem li = new ListItem();
            li.Text = Convert.ToDateTime(i.ToString() + "/1/1900").ToString("MMMM");
            li.Value = i.ToString();
            ddl_maand.Items.Add(li);
        }
    }

非常感谢任何帮助

2 个答案:

答案 0 :(得分:3)

for (int i = 0; i < 12; i++)

我很确定0/1/1900不是有效日期。您可能希望在1开始循环并以12结束:

for (int i = 1; i <= 12; i++)

答案 1 :(得分:1)

@dotctor的相似答案。

private void buttonLoadMonths_Click(object sender, EventArgs e)
{
    comboBoxMonths.DisplayMember = "Value";
    comboBoxMonths.ValueMember = "Key";
    comboBoxMonths.DataSource = GetMonths();
}

private static IEnumerable<KeyValuePair<int, string>> GetMonths()
{
    return Enumerable
        .Range(1, 12).Select(i => new KeyValuePair<int, string>(i, CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i)))
        .ToArray();
}