我正在尝试使用代码隐藏(C#)填充下拉列表。 我不知道如何得到这个。下面是我目前正在尝试使用的代码,但出现错误。 我正在尝试填充一个下拉列表,列出月份的商店(1 - 12)。
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
DropDownListMonth.SelectedValue = i;
DropDownListMonth.DataTextField = i.ToString();
DropDownListMonth.DataValueField = i.ToString();
}
}
听起来您只需要在下拉列表中添加项目即可。如何将List<int>
与foreach
循环一起使用;
List<int> months = new List<int>(){1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
foreach (string month in months)
{
DropDownListMonth.Items.Add(month);
}
因为你的 for 循环工作0
11
而不是1
12
。而且它没有添加任何项目。它只是将SelectedValue
、DataTextField
和DataValueField
设置为11
,不再做任何事情。
这是你需要做的
for (var i = 1; i < 13; i++)
{
var item = new ListItem
{
Text = i.ToString(),
Value = i.ToString()
};
DropDownListMonth.Items.Add(item);
}
您需要一个列表,将值添加到该列表中,并将该列表绑定到下拉列表。
另外,请查看本文以消除一些困惑:所选项目、值等