我想编写这样的代码,以便在运行我的程序时,根据date.time.now自动选择月份下拉列表。我加载页面的月份。
我已经尝试了下面的代码,但是我发现了一个错误:
“不能在下拉列表中选择多项”。
我不知道这意味着什么,因为我没有选择其他项目。
(我的月份下拉列表目前有从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;
}
}为了解决这个问题,我需要在代码中修改什么?或者,是否有其他解决方案可以用于自动选择当前月份?
发布于 2015-07-01 05:46:53
你可以这样做
MonthDropDownList.SelectedIndex = month - 1;发布于 2015-07-01 05:49:13
如果将下拉值生成为月份号,则在page_load事件中
MonthDropDownList.SelectedValue = DateTime.Now.Month.ToString();或者您可以像在代码中那样使用
MonthDropDownList.SelectedIndex= DateTime.Now.Month -1;我总是使用SelectedValue,因为索引在我的公司不可靠:)
发布于 2015-07-01 05:56:50
避免代码中的for循环。
您也可以像这样使用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>
https://stackoverflow.com/questions/31153311
复制相似问题