如何将包含月份的下拉列表设置为上个月

时间:2015-10-02 22:54:55

标签: c# asp.net datetime

我有一个包含月份的下拉列表。我必须将它设置为上个月。我尝试在行DropDownListBM.Items.FindByValue(DateTime.Now.AddMonths(-1).ToString()).Selected = true;

中进行空引用异常

在我的代码下方给出。我认为如果1月是我当前的月份,它有关。

  DateTime month = Convert.ToDateTime("1/1/2000");
                for (int i = 0; i < 12; i++)
                {
                    DateTime NextMont = month.AddMonths(i);
                    ListItem list = new ListItem();
                    list.Text = NextMont.ToString("MMMM");
                    list.Value = NextMont.Month.ToString();
                    DropDownListBM.Items.Add(list);
                }
DropDownListBM.Items.FindByValue(DateTime.Now.AddMonths(-1).ToString()).Selected = true;

1 个答案:

答案 0 :(得分:1)

这样:

DropDownListBM.Items.FindByValue(DateTime.Now.AddMonths(-1).ToString()).Selected = true;

应该是: DropDownListBM.Items.FindByValue(DateTime.Now.AddMonths(-1).Month.ToString()).Selected = true;