Data Binding in Windows Forms
What is Data Binding?
Data binding connects UI controls to data sources (objects, databases, collections) so that changes in one automatically reflect in the other. WinForms provides a robust binding model that works with simple objects, BindingSource
, and complex data sets.
Simple Binding Example
This example demonstrates binding a TextBox
to a property of a custom class.
// Model
public class Person
{
public string Name { get; set; }
}
// Form code
Person person = new Person() { Name = "Alice" };
textBoxName.DataBindings.Add("Text", person, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
Two‑Way Binding Demo
Interact with the form below to see two‑way binding in action. The values you type are reflected instantly in the bound object and displayed on the right.
Bound Object
BindingSource – The Powerhouse
For lists, grids, and complex scenarios, BindingSource
acts as an intermediary that simplifies navigation, currency management, and change notification.
// Model collection
List<Person> people = new List<Person>
{
new Person() { Name = "Bob" },
new Person() { Name = "Carol" }
};
// Binding source
BindingSource source = new BindingSource();
source.DataSource = people;
// Bind to a DataGridView
dataGridView1.DataSource = source;