Handling Threads in a DataGridView in VB .net

1

I am automatically and manually updating a datagridview with data every so often. For this, I delete all the rows and insert them again manually with programmed data. I do not use any database or table.

The problem is that I'm with a thread to not block the GUI, and from that thread I'm deleting and adding the rows. However, after several passes, the system throws "NullReferenceException".

This is my code:

     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
                Dim wreturnCode1 As Integer = System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf RepeatAction), cancellation.Token)
        End Sub

        Private Sub RepeatAction(ByVal obj As Object)
            Dim token As System.Threading.CancellationToken = CType(obj, System.Threading.CancellationToken)
            FormTimer.Enabled = True
            AddHandler FormTimer.Elapsed, AddressOf AutoTaskRepo
       End Sub

       Private Async Sub AutoTaskRepo()
        FormTimer.Enabled = False
        DataGridView1.Rows.Clear()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        FormTimer.Enabled = True

   End Sub

This is the error:

  

Unhandled exception of type 'System.NullReferenceException' in   System.Windows.Forms.dll

     

Additional information: Object reference not established as   instance of an object.

Any solution?
I can not move forward with this.

    
asked by lsalvatore 28.12.2016 в 20:50
source

1 answer

1

Try this code:

DataGridView1.update()
DataGridView1.refresh()

After making any changes to grid .

At some point the grid remains without the rows you are trying to access, or something like that, it will be best to update it after each action.

    
answered by 04.01.2017 в 00:04