如何返回列表框中选择的多个项目的唯一索引值



我在VB中有一个列表框。NET允许用户选择多个类别。我需要把这些类别到一个数据库,并需要从类别的列表框的索引值作为数据库工作的id。SelectedItems(带s)在net应用程序中不起作用。

我尝试了以下代码:

For Each category As ListItem In CategoryListBox.Items
    If category.Selected Then
        Dim courseCategory As New CourseCategory
        courseCategory.CourseID = course.ID
        courseCategory.CategoryID = CategoryListBox.SelectedIndex
        Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
            courseCategoryEntities.CourseCategories.Add(courseCategory)
            courseCategoryEntities.SaveChanges()
        End Using
    End If
Next

在循环中迭代时,代码为:

courseCategory.CategoryID = CategoryListBox.SelectedIndex

第一次运行正确。

在循环的第二次迭代时,它转到下一个选中的项,但是返回第一个选中值的索引。如何返回所选其他索引的值?

这取决于您需要传递给数据库的ID。如果它确实是ListBox中ListItem的索引,那么您应该使用:

courseCategory.CategoryID = CategoryListBox.Items.IndexOf(category); 
然而,这可能不是最好的方法。也许ListItems的顺序改变了,弄乱了索引。您可能希望在每个ListItem上存储实际的CategoryID。Value的性质可以很好地解决这个问题。您可以像这样设置您想要的列作为DataValueField:
<asp:ListBox ID="CategoryListBox" runat="server"
    DataValueField="CategoryID "></asp:ListBox>

所以当你循环遍历ListBox中的每个ListItem并检查它是否被选中时,只需使用它的Value属性。

For Each category As ListItem In CategoryListBox.Items
    If category.Selected Then
        Dim courseCategory As New CourseCategory
        courseCategory.CourseID = course.ID
        courseCategory.CategoryID = category.Value;
        Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
            courseCategoryEntities.CourseCategories.Add(courseCategory)
            courseCategoryEntities.SaveChanges()
        End Using
    End If
Next

修复了保存成功后列表框中取消选择项目的代码。

   End Using
category.Selected = False
End If

我的问题解决了

最新更新