1

我有一个带有 abutton和 a的 windows 窗体datagridview。当我选择button一个线程启动时,它会做一些事情并最终填充我的datagridview. 问题是datagridview没有填充。

我究竟做错了什么?

我的代码:

Private MyCreateStructureFromSampleXMLTread As Thread

Private Sub ButtonCreateStructureFromSampleXML_Click(sender As Object, e As EventArgs) Handles ButtonCreateStructureFromSampleXML.Click
    Me.Cursor = Cursors.WaitCursor
    MyCreateStructureFromSampleXMLTread = New Thread(AddressOf ModuleXML_MESSAGE_STRUCTURE.CreateStructureFromSampleXML)
    MyCreateStructureFromSampleXMLTread.IsBackground = True
    MyCreateStructureFromSampleXMLTread.SetApartmentState(ApartmentState.STA)
    MyCreateStructureFromSampleXMLTread.Start()
    Me.Cursor = Cursors.Default
End Sub

穿线:

    Friend Sub CreateStructureFromSampleXML()
    FormUTool.Cursor = Cursors.WaitCursor
    Try
        If ModuleFileHandling.OpenFile(Application.StartupPath, "Select XML File", ".xml", "XML File (*.xml)|*.xml") = True Then
            ParseXMLFile(PublicUToolVariable.MyOpenedFile)
        End If
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
    ModuleXML_MESSAGE_STRUCTURE.AlignElementPaths(PublicUToolVariable.MyAccessConnection)
    ModuleXML_MESSAGE_STRUCTURE.XML_MESSAGE_STRUCTUREFillDataGridView(PublicUToolVariable.MyAccessConnection)
    FormUTool.Cursor = Cursors.Default
End Sub
4

1 回答 1

1

您正在尝试DataGridView从 UI 线程以外的线程填充。那就是你做错了。UI 元素具有线程关联性要求,要求它们只能从创建它们的线程访问。

更改策略,以便在工作线程中加载和解析 XML,然后将该数据发送到 UI 线程并让 UI 线程填充DataGridView. 这是标准方法。你可以使用BackgroundWorker类。DoWork事件处理程序将在工作线程上执行,而事件RunWorkerCompleted处理程序将在 UI 线程上运行,因此所有封送处理都会为您处理。

于 2013-10-25T14:20:06.727 回答