2014-02-15 145 views
0

我想用后面的代码(C#)填充下拉列表。我不知道如何得到这个。下面是我目前正在尝试使用的代码,但我收到错误。我试图在商店的下拉列表中填入月份(1 - 12)。用c#代码填充下拉列表

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(); 
    } 

} 
+2

你得到这个代码有什么错误? –

回答

1

听起来像你只需要在你的下拉列表中添加项目。如何使用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循环工作011112。并没有添加任何项目。它只是将SelectedValue,DataTextFieldDataValueField设置为11,不做任何事情。

0

您想拥有一个列表,将值添加到该列表中,并将该列表绑定到下拉列表中。

而且,看看这篇文章,以澄清一些困惑:selected item, value, and more

2

这是你需要做的

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