[英]Populating a drop down list with c# code behind
I am trying to populate a drop down list using code behind (C#). 我正在尝试使用(C#)后面的代码填充下拉列表。 I am not sure how to get this.
我不知道如何得到这个。 Below is my code that I am currently trying to use but I am getting errors.
以下是我目前正在尝试使用的代码,但出现错误。 I am trying to populate a drop down list the stores the months ( 1 - 12).
我正在尝试填充存储月份(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();
}
}
Sounds like you just need to add items in your dropdownlist. 听起来您只需要在下拉列表中添加项目即可。 How about using
List<int>
with foreach
loop like; 如何将
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);
}
Because your for loop works 0
to 11
not 1
to 12
. 因为您的for循环适用于
0
到11
而不是1
到12
。 And it is not adding any item. 而且它没有添加任何项目。 It just sets
SelectedValue
, DataTextField
and DataValueField
as 11
, doesn't do anything more. 它只是将
SelectedValue
, DataTextField
和DataValueField
为11
,不再执行其他操作。
This is what you need to do 这就是你要做的
for (var i = 1; i < 13; i++)
{
var item = new ListItem
{
Text = i.ToString(),
Value = i.ToString()
};
DropDownListMonth.Items.Add(item);
}
You want to have a list, add the values to that list, and have that list bound to the dropdown. 您想要一个列表,将值添加到该列表,然后将该列表绑定到下拉列表。
Also, have a look at this article to clear up some confusion: selected item, value, and more 另外,请查看本文以消除一些困惑: 选定的项目,价值等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.