我想编写代码,以便在运行程序时,根据date.time.now自动选择Month Drop Down List。我加载页面的月份。
我已尝试过以下代码,但收到错误消息:
"不能在下拉列表中选择多个项目"。
我不确定这意味着什么,因为我没有选择其他项目。
(我的月份下拉列表目前有从1月到12月的列表项目,用索引0-11表示)
int month = DateTime.Now.Month;
for (int i = 0; i < MonthDropDownList.Items.Count; i++)
{
if (month == 1) //Jan
{
MonthDropDownList.Items[0].Selected = true;
}
else if (month == 2) //Feb
{
MonthDropDownList.Items[1].Selected = true;
}
else if (month == 3) //March
{
MonthDropDownList.Items[2].Selected = true;
}
else if (month == 4) //April
{
MonthDropDownList.Items[3].Selected = true;
}
else if (month == 5) //May
{
MonthDropDownList.Items[4].Selected = true;
}
else if (month == 6) //June
{
MonthDropDownList.Items[5].Selected = true;
}
else if (month == 7) //July
{
MonthDropDownList.Items[6].Selected = true;
}
else if (month == 8) //Aug
{
MonthDropDownList.Items[7].Selected = true;
}
else if (month == 9) //Sept
{
MonthDropDownList.Items[8].Selected = true;
}
else if (month == 10) //Oct
{
MonthDropDownList.Items[9].Selected = true;
}
else if (month == 11) //Nov
{
MonthDropDownList.Items[10].Selected = true;
}
else if (month == 12) //Dec
{
MonthDropDownList.Items[11].Selected = true;
}
}
我需要在代码中更改哪些内容才能解决此问题?或者我可以使用另一种解决方案来自动选择当前月份吗?
答案 0 :(得分:2)
你可以这样做
MonthDropDownList.SelectedIndex = month - 1;
答案 1 :(得分:1)
MonthDropDownList.SelectedValue = DateTime.Now.Month.ToString();
或者您可以像在代码中那样使用
MonthDropDownList.SelectedIndex= DateTime.Now.Month -1;
我总是使用SelectedValue,因为我公司的索引不可靠:)
答案 2 :(得分:1)
避免在代码中循环。
你也可以这样使用 的 C#强>
MonthDropDownList.SelectedValue = DateTime.Now.Month.ToString();
代码
<asp:ListItem Value="1">Jan</asp:ListItem>
<asp:ListItem Value="2">Feb</asp:ListItem>
<asp:ListItem Value="3">March</asp:ListItem>
<asp:ListItem Value="4">Apr</asp:ListItem>
<asp:ListItem Value="5">May</asp:ListItem>
<asp:ListItem Value="6">Jun</asp:ListItem>
<asp:ListItem Value="7">July</asp:ListItem>
<asp:ListItem Value="8">Aug</asp:ListItem>
<asp:ListItem Value="9">Sep</asp:ListItem>
<asp:ListItem Value="10">Oct</asp:ListItem>
<asp:ListItem Value="11">Nov</asp:ListItem>
<asp:ListItem Value="12">Dec</asp:ListItem>
答案 3 :(得分:0)
你不需要声明,条件(if else)就足够了