Cross-thread operation not valid: Control 'DataGridView1'

1.2k Views Asked by At

I have a long running process that was freezing the GUI, that I have moved to a BackgroudWorker thread.

The trouble is, I am getting the following error on the last line of code.

DataGridView1.DataSource = ds.Tables(3)

Cross-thread operation not valid: Control 'DataGridView1' accessed from a thread other than the thread it was created on.

Here is more of the code for context:

Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork

        Dim numToDo As Integer = CInt(e.Argument)

        Dim count As Integer = ListBox1.Items.Count
        For n As Integer = 0 To ListBox1.Items.Count - 1
            Dim l_text As String = CStr(ListBox1.Items(n))

            Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://www.xxx.co.uk/yyy/notice/data.feed?text=" & l_text & "&results-page-size=100&start-publish-date=2015-06-01")

            Dim response As System.Net.HttpWebResponse = request.GetResponse()

            Select Case response.StatusCode

                Case System.Net.HttpStatusCode.OK

                    Dim stream As System.IO.Stream = response.GetResponseStream()
                    Dim reader As New System.IO.StreamReader(stream)

                    Dim document As New System.Xml.XmlDocument()

                    document.LoadXml(contents)

                    Dim ds As DataSet
                    ds = New DataSet()
                    ds.ReadXml(New XmlNodeReader(document))

                    If ds.Tables.Count <= 4 Then

                        'Do Nothing

                    Else

                        DataGridView1.DataSource = ds.Tables(3)

I understand that I am not allowed to cross thread a background worker task with other tasks. But I am confussed because the Datagridview is defined in the the DoWork thread. So I don't believe I am trying to cross thread?

Any help greatly appreciated.

0

There are 0 best solutions below