WinForms Data Binding Tutorial
Introduction
Data binding connects UI controls to data sources, allowing automatic synchronization of values. This tutorial guides you through basic and advanced scenarios using Windows Forms.
What is Data Binding?
WinForms supports several binding types:
- Simple binding – bind a single property.
- Complex binding – bind to a list or collection.
- Two‑way binding – changes propagate both ways.
Simple Example
Bind a TextBox
to a Customer.Name
property.
public partial class Form1 : Form
{
private Customer _customer = new Customer { Name = "Alice" };
public Form1()
{
InitializeComponent();
textBoxName.DataBindings.Add("Text", _customer, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
public class Customer : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
if (_name != value) { _name = value; OnPropertyChanged(nameof(Name)); }
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string prop) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
Binding to a List
Display a collection of objects in a DataGridView
using a BindingList
.
public partial class Form2 : Form
{
private BindingList _products = new BindingList
{
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Smartphone", Price = 599.49m },
};
public Form2()
{
InitializeComponent();
dataGridViewProducts.AutoGenerateColumns = true;
dataGridViewProducts.DataSource = _products;
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Two‑Way Binding
Synchronize a ComboBox
selection with a property on the current object.
public partial class Form3 : Form
{
private BindingSource _bs = new BindingSource();
public Form3()
{
InitializeComponent();
var colors = new List { "Red", "Green", "Blue" };
_bs.DataSource = new Settings { SelectedColor = "Green" };
comboBoxColors.DataSource = colors;
comboBoxColors.DataBindings.Add("SelectedItem", _bs, "SelectedColor", true, DataSourceUpdateMode.OnPropertyChanged);
}
}
public class Settings : INotifyPropertyChanged
{
private string _selectedColor;
public string SelectedColor
{
get => _selectedColor;
set { if (_selectedColor != value){ _selectedColor = value; OnPropertyChanged(nameof(SelectedColor)); } }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Summary
Data binding simplifies UI development by reducing boilerplate code. Explore more advanced topics such as custom formatters, currency managers, and binding validation in the Advanced Binding guide.