开发者

WinForm: Obtain values from selected items in a List Box

How do I obtain the values (not displayed text) of all the selected items in a List Box开发者_StackOverflow社区?

My intention is to use the values (which represent primary and foreign keys in my databases) to assemble a sql query.

Specs: Using WinForm with a .Net Framework v.4


You can also use any object you like in a list box. Small example below, but to test you'll have to create a form with a ListBox and button on it. Same idea as the dictionary but this will work with more complex objects.

Public Class Form1

    Dim tests As New List(Of Test)

    Class Test
        Private _Key As Integer
        Public Property Key() As Integer
            Get
                Return _Key
            End Get
            Set(ByVal value As Integer)
                _Key = value
            End Set
        End Property


        Private _value As String
        Public Property Value() As String
            Get
                Return _value
            End Get
            Set(ByVal value As String)
                _value = value
            End Set
        End Property
    End Class

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        With tests
            .Add(New Test With {.Key = 1, .Value = "Val1"})
            .Add(New Test With {.Key = 2, .Value = "Val2"})
            .Add(New Test With {.Key = 3, .Value = "Val3"})
        End With

        ListBox1.SelectionMode = SelectionMode.MultiSimple
        ListBox1.DisplayMember = "Value"

        For Each t In tests
            ListBox1.Items.Add(t)
        Next

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each t As Test In ListBox1.SelectedItems
            Debug.WriteLine(t.Key)
        Next
    End Sub

End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜