I have a DataGridView control that I’m filling with data from a database. Since the queries have the possibility of returning a lot of data I decided to use a BackgroundWorker object to pull the data so my application wouldn’t appear to be frozen when the query was running. I can get that to work just fine but it didn’t solve my overall problem. After pulling the data I set the DataGridView’s Datasource to it and then call a method that sets up all kinds of formatting on the DataGridView object. It loops through the columns and rows and does things like set background color, alignment, and tool tips on cells based on the data. This is all quite time consuming and my application appears to freeze up when it runs. However I’m having trouble trying to get this into a BackgroundWorker. I’ve tried two methods...
Method One:
If I pass in my DataGridView object as an argument in the BackgroundWorker I get a cross-threading error when I try to set the DataSource. This is how I've always "packaged" things to go into a background worker and I haven't run into problems before...am I not doing it correctly?
Private Class packageFormatGrid
Public dt As DataTable
Public dgv1 As DataGridView
End Class
Private Sub CallFormat(ByRef dt as DataTable)
Dim package As New packageFormatGrid
package.dt = dt
package.dgv1 = dgvOutput
bgwFormat.RunWorkerAsync(package)
End Sub
Private Sub bgwFormat_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwFormat.DoWork
Dim package As packageFormatGrid = CType(e.Argument, packageFormatGrid)
package.dgv1.DataSource = package.dt
End Sub
Method Two:
If I declare a new DataGridView object and pass it to the RunWorkerComplete as the result, and there set my real DataGridView equal to it, I don’t get any errors, but my grid simply doesn’t fill with anything.
Private Sub bgwFormat_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwFormat.DoWork
Dim package As packageFormatGrid = CType(e.Argument, packageFormatGrid)
Dim dgv As New DataGridView
dgv.DataSource = package.dt
FormatOutputGrid(dgv)
e.Result = dgv
End Sub
Private Sub bgwFormat_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwFormat.RunWorkerCompleted
Dim dgv As DataGridView = CType(e.Result, DataGridView)
dgvOutput = dgv
End Sub
It’s Monday, so I’m suspicious that I’m just not thinking clearly and I’m missing something painfully obvious. When I google all I get is articles about pulling the data with a BackgroundWorker and nothing about formatting the grid. Does anyone have any ideas?