获取Listbox的所有值作为列表

时间:2014-05-12 12:41:32

标签: winforms listbox vb.net-2010

这应该很简单,但对我来说当然不是很简单。我有两个列表框,一个绑定到数据表,另一个绑定到任何东西。用户可以从绑定列表框中选择记录,并将它们添加到未绑定的列表框中。我想以列表的形式检索未绑定框的内容,并将列表作为输入提供给另一个类,我很难从未绑定的列表框中获取值。这就是我的代码:

    Dim selectedT = (From i In lbSelectedT.Items).ToList()

    For Each T In selectedT
        MsgBox(T.ToString)

    Next

    ' output is: System.Data.DataRowView

我做得不对?

1 个答案:

答案 0 :(得分:0)

您的第二个列表框应与第一个列表框绑定。然后循环遍历项目时,它们就像源数据一样对待它们。

以下内容绑定到listOption对象列表。单击button2时,它会遍历项目,隐式将它们转换为listOption,然后访问数据。

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        options.Add(New listOption("test 1", 1))
        options.Add(New listOption("test 2", 2))
        options.Add(New listOption("test 3", 3))
        options.Add(New listOption("test 4", 4))

        ListBox1.DataSource = options


        ListBox1.DisplayMember = "name"
        ListBox1.ValueMember = "id"

        ListBox2.DisplayMember = "name"
        ListBox2.ValueMember = "id"

    End Sub

    Public Property options As New List(Of listOption)
    Public Class listOption
        Public Property name As String
        Public Property id As Integer

        Sub New(name As String, id As String)
            Me.name = name
            Me.id = id
        End Sub
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ListBox1.SelectedItem IsNot Nothing Then
            ListBox2.Items.Add(ListBox1.SelectedItem)
        End If
    End Sub


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim selectedT = (From i In ListBox2.Items).ToList()

        For Each T As listOption In selectedT
            MsgBox(T.name.ToString)

        Next
    End Sub
End Class