I'm trying to use a BackgroudWorker to load data into a DataTable and then return it to a DataGridView.
Public Sub Reload_Selected_Invoice()
bgwLoadOldInvoices.RunWorkerAsync()
End Sub
Private Sub bgwLoadOldInvoices_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwLoadOldInvoices.DoWork
Dim DataTable As New DataTable
Using SQLSERVER_Connection As New SqlConnection("Server = localhost;Database=test;Integrated Security=SSPI;")
Using SQLQuery As New SqlCommand("SQLQuery that takes a few seconds;", SQLSERVER_Connection)
SQLSERVER_Connection.Open()
Using SqlDataAdapter As New SqlDataAdapter(SQLQuery)
SqlDataAdapter.Fill(DataTable)
End Using
SQLSERVER_Connection.Close()
End Using
End Using
e.Result = DataTable
End Sub
Private Sub bgwLoadOldInvoices_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgwLoadOldInvoices.RunWorkerCompleted
dgvOldInvoices.DataSource = e.Result
End Sub
When I push the button the form stops responding until the query is finished. This is my first attempt with Threading and I don't see where I'm messing up.
Edit 1
Private Sub bgwLoadOldInvoices_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgwLoadOldInvoices.DoWork
Dim DataGridView1 As New DataGridView
Dim DataTable As New DataTable
Using SQLSERVER_Connection As New SqlConnection("Server = localhost;Database=test;Integrated Security=SSPI;")
Using SQLQuery As New SqlCommand("SQLQuery that takes a few seconds;", SQLSERVER_Connection)
Using SqlDataAdapter As New SqlDataAdapter(SQLQuery)
SqlDataAdapter.Fill(DataTable)
End Using
End Using
End Using
DataGridView1.DataSource = DataTable
e.Result = DataGridView1
End Sub
Private Sub bgwLoadOldInvoices_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bgwLoadOldInvoices.RunWorkerCompleted
dgvOldInvoices = DirectCast(e.Result, DataGridView)
dgvOldInvoices.Refresh()
MessageBox.Show("Finished!")
End Sub