asp.net中的列表框未获取所选项目

我的网页上有多个下拉列表和列表框。

我试图从lstCatID列表框中获取CategoryID列表,我能够使用类别名称填充列表框。

如果我在第一次尝试中记得正确,我的代码工作正常,之后我做了一些改变然后它声明总是得到第一个项目选择x时间的数量

   protected void Button1_Click(object sender, EventArgs e) { string CatID = string.Empty; foreach (ListItem li in lstCatID.Items) { if (li.Selected == true) { // Response.Write(); CatID += lstCatID.SelectedItem.Value + ","; } } Response.Write(CatID); } 

我不知道出了什么问题我检查MSDN它显示完全相同的方式。

可能是我做错了什么。

只是使用firefox添加我能够看到多个选中的值都选择了属性。

 One Two Three Four Five 

在这种情况下,我的输出将是3,3,3

在这方面,我将不胜感激

您每次都将其设置为相同的值:

 foreach (ListItem li in lstCatID.Items) { if (li.Selected == true) { // you are always using lstCatID.SelectedItem.Value. CatID += lstCatID.SelectedItem.Value + ","; } } 

当您真正想要所选循环中项目的值时:

 foreach (ListItem li in lstCatID.Items) { if (li.Selected == true) { // get the value of the item in your loop CatID += li.Value + ","; } } 

我不确定我使用的逻辑有什么问题。

我使用LINQ找到了一个很好的解决方案。

这个单一的陈述效果很好,并得到了我想要的结果。

 string values = String.Join(", ", lstCatID.Items.Cast().Where(i => i.Selected).Select(i => i.Value).ToArray()); 

结果:3,29,25

尝试在Page_Load上添加Page.IsPostback

 protected void Page_Load(object sender, EventArgs e) { // Do your API code here unless you want it to occur only the first // time the page loads, in which case put it in the IF statement below. if (!Page.IsPostBack) { } } 

码:

 protected void Button1_Click(object sender, EventArgs e) { string CatID = string.Empty; foreach (ListItem li in lstCatID.Items) { if (li.Selected ) { // TODO: Whatever you are doing with a selected item. } } Response.Write(CatID); } 

一旦我遇到同样的问题,我犯了Postback错误。

希望它有效。

使用linq获取所选项目

 var selected = lstCatID.Items.Where(i => i.Selected); 

几分钟后,我找到了一个解决方案:

 If lstLocations.Items.Count > 0 Then For i As Integer = 0 To lstLocations.Items.Count - 1 If lstLocations.Items(i).Selected Then 'insert command Dim selectedItem As String = lstLocations.Items(i).Text End If Next End If 

这在我的场景中运行良好