Saturday, November 5, 2011

Visual Basic .Net – Binding to Windows Forms Controls


The .NET Framework brings a wide variety of controls to the developer. The Windows Forms controls are found in the System.Windows.Forms namespace, and the vast majority of them support data binding. In general, data binding to a control is far from challenging. It requires that you use an in-memory data store and can usually accept either a DataTable or a DataSet.
The mechanism is very simple. Take a look at the following example, using a DataTable:
Dim adapter As New OleDbDataAdapter("Select * From Customers", _ connStr)
Dim dt As New DataTable()

' Import the query results into the DataTable
adapter.Fill(dt)

' Bind the DataTable to the DataGrid
DataGrid1.DataSource = dt
The DataSet works in almost exactly the same way:
Dim adapter As New OleDbDataAdapter("Select * From Customers", connStr)
Dim ds As New DataSet()

' Import the query results into the DataSet
adapter.Fill(ds)

' Bind a DataTable from the DataSet to the DataGrid
DataGrid1.DataSource = ds.Tables("Customers")
Notice in this example that instead of passing the entire DataSet to the DataGrid, weve chosen to bind only a single table. This is often necessary with controls for which multiple sets of tables dont make sense. The DataGrid is not one of these controls, however. It is capable of a multitable display (try it) and likes the DataSet just fine.

No comments:

Post a Comment