1

我有listbox1VB 2010,它绑定到数据源并显示数据集中的值。我使用设计器绑定它——即不是通过代码。我刚刚在 的属性中选择了数据源listbox1

现在我想检索选定的值。当我将列表框保留为单选时,然后ListBox1.SelectedValue.ToString完成工作 - 它为我提供了所选项目的文本。

但我需要它来允许多项选择。这是我的代码:

    Dim items As ListBox.SelectedObjectCollection
    items = ListBox1.SelectedItems
    For Each i As String In items
        MsgBox(i)
    Next

这是我得到的错误:

Conversion from type 'DataRowView' to type 'String' is not valid.

我尝试了几种不同的方法来获取所选项目的值,但似乎没有任何直接的方法可以做到这一点。这是不可能的吗?是否有必要声明一个新数据集并以编程方式填充列表框或其他什么?

4

3 回答 3

2
For Each drv As DataRowView In ListBox1.SelectedItems
        MessageBox.Show(drv.Item(0).ToString)
    Next
于 2012-11-23T17:34:09.427 回答
0

在我的脑海中,我认为你可以这样做:

Dim items As ListBox.SelectedObjectCollection
items = ListBox1.SelectedItems
For Each i As ListViewItem In items
    MsgBox(i.Value.ToString())
Next
于 2012-11-23T17:24:37.583 回答
-1

看看我的问题和答案。它允许您将数据库中的各个条目分解为列表框。

在表单中添加 2 个列表框和一个文本框,然后复制此代码,您必须替换自己的服务器和数据库等条目。

Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' get the data
    Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
    Dim mySQLConnection As New SqlConnection(SQLConnectionString)

    ' Populate the list box using an array as DataSource. 
    mySQLConnection.Open()
    Dim SQLDataTable As New System.Data.DataTable

    'Create new DataAdapter
    Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
    mySQLDataAdapter.Fill(SQLDataTable)
    ListBox1.DataSource = SQLDataTable
    ListBox1.DisplayMember = "RivetType"

    ' remove validation data from list
    Dim Count As Integer
    Dim X As Integer
    'get the column of data to search for
    For Count = 0 To ListBox1.DataSource.Columns.Count - 1
        X = InStr(ListBox1.DataSource.Columns.Item(Count).ToString, "Name")
        If X <> 0 Then Exit For
    Next
    ' now search for any invalid rows, in that column. those containing "---"
    Dim TheTable As DataTable = CType(ListBox1.DataSource, DataTable)
    Dim theRow As DataRow() = TheTable.Select()
    Dim RowNumber As Integer
    For RowNumber = 0 To UBound(theRow) - 1
        If theRow(RowNumber).Item(Count).ToString <> "---" Then
            ' data is OK so transer it to the other listbox
            ListBox2.Items.Add(theRow(RowNumber).Item(Count - 1).ToString)
        End If
    Next

    ListBox2.ClearSelected()
End Sub 'NewNew

Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
    TextBox1.Text = ListBox2.SelectedItem.ToString()
End Sub
End Class 'ListBoxSample3
于 2016-01-07T15:22:46.807 回答