Data Binding in Windows Forms (VB.NET)
Data binding connects UI elements to data sources such as objects, collections, or databases, simplifying the synchronization between the interface and the underlying data.
Key Concepts
- BindingSource – Mediates between controls and data.
- DataMember – Specifies which list or property to bind to.
- DataSource – The actual data object or collection.
- Formatting & Parsing – Convert values between UI and data source.
Simple Binding Example
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim customers = GetCustomers()
TextBoxName.DataBindings.Add("Text", customers, "Name")
TextBoxCity.DataBindings.Add("Text", customers, "City")
End Sub
Private Function GetCustomers() As BindingList(Of Customer)
Return New BindingList(Of Customer) From {
New Customer With {.Name="Alice", .City="Seattle"},
New Customer With {.Name="Bob", .City="Portland"}
}
End Function
End Class
Public Class Customer
Public Property Name As String
Public Property City As String
End Class
Binding a DataGridView
Private Sub LoadGrid()
Dim ds As New DataSet()
Using conn As New SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM Products", conn)
da.Fill(ds, "Products")
End Using
Dim bs As New BindingSource()
bs.DataSource = ds.Tables("Products")
DataGridView1.DataSource = bs
End Sub
Advanced: Formatting Example
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim list As New BindingList(Of Order) From {
New Order With {.OrderId=1001, .Total=1234.5D},
New Order With {.OrderId=1002, .Total=987.65D}
}
BindingSource1.DataSource = list
DataGridView1.DataSource = BindingSource1
Dim totalCol = DataGridView1.Columns("Total")
AddHandler totalCol.DefaultCellStyle.Format, Sub(s,ea)
ea.Value = String.Format("{0:C}", ea.Value)
End Sub
End Sub
Public Class Order
Public Property OrderId As Integer
Public Property Total As Decimal
End Class
Reference Table
Property | Description |
---|---|
DataSource | The object that provides the data. |
DataMember | Name of the list or property within the DataSource. |
FormatString | String used to format displayed values. |
NullValue | Value used when the bound data is DB null. |