如何通过其索引获取 ListBox 项的 ValueItem 值

How to get the ValueItem value of ListBox item by its index

我有一个列表框,其中存储了一个描述和一个值(描述是客户名称,值项是该客户在数据库中的 ID)在我的表单上,我有两个列表框,左边的那个有一个完整的客户名称列表,然后用户从该列表中选择并将他们想要与用户关联的名称添加到右侧的列表框中。当我来保存记录时,我想将客户 ID 列表存储在 table 中,以便我可以识别该记录与哪些客户相关。

我的代码使用 For 遍历列表。下一个循环:

For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).Value.ToString() & ","
Next

U 是一条用户记录 class,字段 CustomersLinkedTo 是一个 NVarchar(255) 字段,我将构建一个逗号分隔的列表,其中包含用户已将此用户分配给的 CustomerID。

问题是 lbxCustomerList.Items(n).Value 是不允许的。我正在使用 VB.NET 和 Dot Net Framework V4。

我尝试将 ListBox 加载到 ListBox.ObjectCollection 变量中,然后查看是否允许我访问 ValuItems,但也不允许。我如何获取与描述文本相反的值?

编辑 **** 为了帮助那些试图帮助我的好人,我在下面添加了我用来填充客户列表的代码,然后是我用来填充包含他们选择的客户的 lbxCustomersLinkedTo 的代码:

填充左侧的列表,用户从中选择客户名称,并将它们添加到右侧的列表中,该列表包含用户要分配给用户的子集。

    Private Sub PopulateCustomerList()
    Dim c As New Customer()
    Dim cc As New ArrayList()

    Try
        'Clear list
        lbxCustomerList.Items.Clear()
        lbxCustomerList.DataSource = Nothing

        'Populate from DB.
        cc = c.GetCustomersForDropLists(customerTypeEnum.Active)
        lbxCustomerList.DataSource = cc
        lbxCustomerList.DisplayMember = "DisplayedText"
        lbxCustomerList.ValueMember = "ReturnedID"
        lbxCustomerList.Refresh()

    Catch ex As Exception
        PEH("PopulateCustomerList", "frmUserSetup", ex.Message)
    End Try
End Sub

将用户从客户列表中选择的项目添加到我感兴趣的项目的代码,我用它来派生我要添加到我的用户记录中的客户 ID 列表。

   Private Sub AddToList()
    Dim SelItems As New ListBox.SelectedObjectCollection(lbxCustomerList)
    SelItems = lbxCustomerList.SelectedItems

    Try

        If lbxCustomerList.SelectedItems.Count > 0 Then
            For n = 0 To SelItems.Count - 1
                lbxCustomersLinkedTo.Items.Add(SelItems(n))
            Next
            lbxCustomerList.ClearSelected()
        End If

    Catch ex As Exception
        PEH("AddToList", "frmUserSetup", ex.Message)
    End Try
End Sub

这是我正在谈论的用户表单部分的图像:

@ThePeter - 感谢您的例程稍加修改就成功了。

这是我现在保存例程中的代码:

           'Get the Customers an officer works for into a comma separated list.
        'First remove any existing items.
        U.CustomersLinkedTo = ""

        If (lbxCustomersLinkedTo.Items.Count > 0) Then
            For n = 0 To lbxCustomersLinkedTo.Items.Count - 1
                If n = lbxCustomersLinkedTo.Items.Count - 1 Then
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) 'Don't add comma to last item.
                Else
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) & ","
                End If
            Next
        End If

这是您的例程,因为它最初给出了一个错误,因此稍作修改:

   ''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
                Catch ex As Exception
                    PEH("WhatValueIsSelectedInListBoxForIndex - Populated Code section", "frmUserSetup", ex.Message)
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Ex As Exception

        PEH("WhatValueIsSelectedInListBoxForIndex", "frmUserSetup", Ex.Message)
        sReturn = ""
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn

End Function

我必须修改以适合我的列表框的那一行是:

                       'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID

在您的帮助下,现在可以直接填充数据库字段了。

Siv

删除 .Value 部分或改用此代码

For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).ToString() & ","
Next

你可以更轻松地使用@LarsTech 所说的内容 这不需要循环

U.CustomersLinkedTo = String.Join(", ", lbxCustomerList.Items)

此函数将允许您查找列表框中所选内容的值。您可以使用它来获取所选项目的 "hidden" 值或列表框中项目的显示值。

更新:我调整了函数,使其根据原始问题根据索引值工作

Public Enum SelectByMode As Integer
   ByDisplayName = 1
   ByReturnValue = 2
End Enum

''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnValue
                Catch Exp As Exception
                    '
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Exp As Exception
        'You do whatever you want to do here when an error occurs.
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn
End Function