在 2.0 中使用时,出现错误,跨线程操作无效:从创建它的线程以外的线程访问控制 'ListView1'

when use in 2.0, i got the error,Cross-thread operation not valid: Control 'ListView1' accessed from a thread other than the thread it was created on

请帮我转换编码...

Public Sub FillListView(ByVal lstbox As ListView, ByVal colwidth As Integer, ByVal dset As DataSet)
    Dim c As DataColumn
    For Each c In dset.Tables(0).Columns
        Dim h As New ColumnHeader
        h.Text = c.ColumnName
        h.Width = colwidth
        ' lstbox.Invoke(
        lstbox.Columns.Add(h) ''Problem here
        ') 
    Next

    Dim dt As DataTable = dset.Tables(0)
    Dim str(dset.Tables(0).Columns.Count) As String

    Dim rr As DataRow
    For Each rr In dt.Rows
        For col As Integer = 0 To dset.Tables(0).Columns.Count - 1
            str(col) = rr(col).ToString()
        Next
        Dim ii As New ListViewItem(str)
        lstbox.Items.Add(ii) ''Problem here
    Next
End Sub

推测您必须从 UI 线程以外的线程调用它。为了修复它,您需要调用回 UI 线程。这是您可以做到的一种方法:

Public Delegate Sub FillListView(ByVal lstbox As ListView, ByVal colwidth As Integer, ByVal dset As DataSet)

Public Sub FillListView(ByVal lstbox As ListView, ByVal colwidth As Integer, ByVal dset As DataSet)

    ' Invoke back to the UI thread, if necessary
    If lstbox.InvokeRequired Then
        lstbox.Invoke(New FillListViewDelegate(AddressOf FillListView), listbox, colWidth, dset))
        Exit Sub
    End If

    Dim c As DataColumn
    For Each c In dset.Tables(0).Columns
        Dim h As New ColumnHeader
        h.Text = c.ColumnName
        h.Width = colwidth
        lstbox.Columns.Add(h)
    Next

    Dim dt As DataTable = dset.Tables(0)
    Dim str(dset.Tables(0).Columns.Count) As String

    Dim rr As DataRow
    For Each rr In dt.Rows
        For col As Integer = 0 To dset.Tables(0).Columns.Count - 1
            str(col) = rr(col).ToString()
        Next
        Dim ii As New ListViewItem(str)
        lstbox.Items.Add(ii)
    Next
End Sub