繁体   English   中英

使用C#代码填充下拉列表

[英]Populating a drop down list with c# code behind

我正在尝试使用(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循环适用于011而不是112 而且它没有添加任何项目。 它只是将SelectedValueDataTextFieldDataValueField11 ,不再执行其他操作。

这就是你要做的

for (var i = 1; i < 13; i++)
{
    var item = new ListItem
        {
            Text = i.ToString(),
            Value = i.ToString()
        };
    DropDownListMonth.Items.Add(item);
}

您想要一个列表,将值添加到该列表,然后将该列表绑定到下拉列表。

另外,请查看本文以消除一些困惑: 选定的项目,价值等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM