VB.NET•Whip Out Fire-and-Forget DataGrid Loading

Listing 7. A "fire and forget" mechanism enables you to load a DataSet into a DataGrid. Simply write code that grabs a DataSet on a worker thread, then loads your retrieved data into a DataGrid. This is useful when you have multiple data retrieval methods that are not necessarily dependent on each other.

Private _updateThread As Thread
Private _updateThreadStart As _
   New ThreadStart(AddressOf GetData)

Private _ds As DataSet
Private _currentDatabase As String
Private _currentTableName As String

Private Sub LoadSelectedTableData _
   (ByVal Database As String, _
   ByVal TableName As String)

   Me.Cursor = Cursors.AppStarting

   _currentDatabase = Database
   _currentTableName = TableName

   _updateThread = New _
      Thread(_updateThreadStart)
   _updateThread.Start()

End Sub

Public Sub BindData()
   ' Bind the data to the DataGrid
   If _ds.Tables.Count > 0 Then
      DataGrid1.DataSource = _
         _ds.Tables(0)
      _ds = Nothing
   End If

   Me.Cursor = Cursors.Default
End Sub

Public Sub GetData()
   _ds = New DataSet
   _ds = _dbHelper.GetTableData _
      (_currentDatabase, _
      _currentTableName)

   If _ds.Tables.Count > 0 Then
      Dim _bindDataGrid As New _
         MethodInvoker _
         (AddressOf Me.BindData)

      If Me.DataGrid1.InvokeRequired Then
         Me.Invoke(_bindDataGrid)
      Else
         BindData()
      End If
   End If
End Sub