"conversion from type 'datarowview' to type 'string' is not valid "在清单框上 vb.net

"conversion from type 'datarowview' to type 'string' is not valid "on Checklistbox vb.net

我的清单框有问题。它在清单框中有主题名称,我想弹出消息主题是什么用户被选中

For Each Item As String In CheckedListBox_subject.CheckedItems
            MsgBox(Item)
Next

我得到了错误

"conversion from type 'datarowview' to type 'string' is not valid"

CheckedListBox_subject.CheckedItems

然后使用正确的类型:

For Each Item As DataRowView In CheckedListBox_subject.CheckedItems
     Dim text As String = Item(0).ToString() ' or any other column, you can also use the string overload
     MsgBox(text)
Next

当DataSource为DataTable时如下所示

有关更多信息,请参阅我在 Microsoft 的 code article

Public Class Form1
    ''' <summary>
    ''' clbCheckedListBox is our CheckedListBox
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Form1_Load(sender As Object, e As EventArgs) _
        Handles MyBase.Load

        Dim dt As New DataTable With {.TableName = "MyTable"}

        dt.Columns.Add(New DataColumn With {.ColumnName = "Identifier",
                                            .DataType = GetType(Int32),
                                            .AutoIncrement = True,
                                            .AutoIncrementStep = 100,
                                            .AutoIncrementSeed = 100})

        dt.Columns.Add(New DataColumn With {.ColumnName = "ItemName",
                                            .DataType = GetType(String)})

        dt.Columns.Add(New DataColumn With {.ColumnName = "ExtraData",
                                            .DataType = GetType(String)})


        dt.Rows.Add(New Object() {Nothing, "One", "Extra 1"})
        dt.Rows.Add(New Object() {Nothing, "Two", "Extra 2"})
        dt.Rows.Add(New Object() {Nothing, "Three", "Extra 3"})
        dt.Rows.Add(New Object() {Nothing, "Four", "Extra 4"})
        dt.Rows.Add(New Object() {Nothing, "Five", "Extra 5"})

        clbCheckedListBox.DataSource = dt
        clbCheckedListBox.DisplayMember = "ItemName"
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim Checked As CheckedListBox.CheckedItemCollection =
            clbCheckedListBox.CheckedItems

        If Checked.Count = 0 Then
            Exit Sub
        End If

        ' Conventional  method to react
        For Each drv As DataRowView In Checked

            Console.WriteLine("{0} {1}",
                              drv.Row.Field(Of Integer)("Identifier"),
                              drv.Row.Field(Of String)("ItemName"),
                              drv.Row.Field(Of String)("ExtraData")
                              )

        Next
    End Sub
End Class