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

时间:2016-05-17 01:05:04

标签: vb.net visual-studio-2008

请帮我转换编码......

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

1 个答案:

答案 0 :(得分:0)

据推测,你必须从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