WinForm:从列表框中的选定项目获取值

时间:2010-08-26 15:50:44

标签: winforms listbox

如何获取列表框中所有选定项目的值(不显示文本)?

我的目的是使用值(表示我的数据库中的主键和外键)来汇编SQL查询。

规范:将WinForm与.Net Framework v.4一起使用

1 个答案:

答案 0 :(得分:1)

您还可以在列表框中使用任何您喜欢的对象。下面的小例子,但为了测试你必须创建一个带有ListBox和按钮的表单。 与字典相同的想法,但这将适用于更复杂的对象。

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
相关问题