我有一个带有button
和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
答案 0 :(得分:1)
您正试图从UI线程以外的线程填充DataGridView
。这就是你做错了。 UI元素具有线程亲和力要求,要求只从创建它们的线程访问它们。
更改策略,以便在工作线程中加载和解析XML,然后将该数据发送到UI线程,让UI线程填充DataGridView
。这是标准方法。您可以使用BackgroundWorker
课程。 DoWork
事件处理程序将在工作线程上执行,RunWorkerCompleted
事件处理程序将在UI线程上运行,因此将为您处理所有编组。