BindingSource and BindingList
A grid bound to a list is the normal way a WinForms application shows data. Between the grid and the list sits a small layer with two parts: BindingList<T>, a list that reports its changes, and BindingSource, the object that carries a position and connects one list to several controls. Both are plain .NET code, so the half of the mechanism that matters runs on this machine.
BindingSource
A BindingSource is a component with a DataSource, a position in that data and a Current item. A grid, a text box and a label can all be bound to the same source, and they agree on which record is being looked at:
- DataSource and DataMember: the list, or a table of a DataSet, and the property of the item to use when the data source is an object rather than a list.
- Position, Count, MoveNext() and MovePrevious(): the cursor. A BindingNavigator is a toolbar of buttons that call exactly these.
- Current: the item at the position, as an object. PositionChanged and CurrentChanged are the events, and CurrentItemChanged is the one a form usually wants.
- Sort and Filter: a sort and a filter string over a DataTable, or over a list with IBindingListView. They do nothing for a plain BindingList
- EndEdit() and CancelEdit(): commit or discard the edit that a bound control is making. A Save button calls EndEdit before it reads the item, because the grid commits the cell only when the focus leaves it.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly BindingList<Note> _notes = new()
{
new() { Title = "one" },
new() { Title = "two" },
new() { Title = "three" },
};
public Form1()
{
Text = "One source, three controls";
ClientSize = new Size(420, 220);
var source = new BindingSource { DataSource = _notes };
var grid = new DataGridView
{
Location = new Point(16, 16),
Size = new Size(388, 120),
DataSource = source,
AllowUserToAddRows = false,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
};
var title = new TextBox { Location = new Point(16, 150), Width = 388 };
title.DataBindings.Add(nameof(TextBox.Text), source, nameof(Note.Title), true);
var position = new Label { Location = new Point(16, 186), AutoSize = true };
source.PositionChanged += (sender, e) => position.Text = $"{source.Position + 1} of {source.Count}";
Controls.Add(grid);
Controls.Add(title);
Controls.Add(position);
}
}
internal sealed class Note
{
public string Title { get; set; } = string.Empty;
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The grid and the text box are bound to one source, so choosing a row in the grid writes that note's title into the box, and typing in the box writes it back into the note. DataBindings.Add(property, source, member, formattingEnabled) is the call; the fourth argument is what makes a DateTime formatted by the control's culture instead of calling ToString.
A BindingSource is also the answer to the question a form asks when it has two views of one list: a grid and a list box, a detail panel and a table. Binding both to the source keeps them on the same record, and the position is the only state that has to be shared.
BindingList
BindingList<T> is a List<T> that raises ListChanged when it changes, which is what a bound control listens to. The event's ListChangedType says what happened:
- ItemAdded and ItemDeleted: a row appeared or went away. NewIndex is its position, and for a delete it is the index the item had.
- ItemChanged: the item at NewIndex changed. The list raises it when the item is replaced or when the list is told about the change; a property set on the item itself raises nothing unless the item implements INotifyPropertyChanged, which is the next lesson.
- Reset: the whole list changed, usually by a sort. A bound grid rebuilds every row.
- ItemMoved: a position changed, when AllowNew and a sorted view move a new row into place.
- AllowNew and AllowRemove: whether AddNew() and Remove() work. AllowEdit is the same for an item.
- RaiseListChangedEvents: turn the events off while a bulk change runs and back on at the end, which is what BeginUpdate does for the control.
- AddingNew and AddingNewItem: where a new item comes from when it needs a default value the type cannot give itself.
The four kinds of change
The event is what a grid uses to redraw one row instead of all of them, and it is also how a form keeps a count in step. The distinction that matters in practice is between a change to the list and a change to an item:
A BindingList of plain objects reports adds and removes and says nothing about an edit, because it has no way to know that a property was set. The run below makes exactly that point with a count.
A list that reports its changes
This program adds two notes, edits one and removes one, and prints every event together with the number of changes it made. It runs here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
var notes = new BindingList<Note>();
var events = new List<string>();
var changes = 0;
notes.ListChanged += (sender, e) => events.Add($"{e.ListChangedType,-9} index {e.NewIndex}");
var first = new Note { Title = "one" };
notes.Add(first);
changes++;
notes.Add(new Note { Title = "two" });
changes++;
first.Title = "one, edited";
changes++;
notes.RemoveAt(0);
changes++;
foreach (var line in events)
{
Console.WriteLine(line);
}
Console.WriteLine($"notes: {notes.Count}, first: {notes[0].Title}");
Console.WriteLine($"changes: {changes}, events: {events.Count}");
Console.WriteLine($"AllowNew: {notes.AllowNew}, AllowRemove: {notes.AllowRemove}");
Console.WriteLine($"with INotifyPropertyChanged the edit would add one");
internal sealed class Note
{
public string Title { get; set; } = string.Empty;
}
dotnet run
ItemAdded index 0
ItemAdded index 1
ItemDeleted index 0
notes: 1, first: two
changes: 4, events: 3
AllowNew: True, AllowRemove: True
with INotifyPropertyChanged the edit would add one
The output is the real run. Four changes produced three events, and the missing one is the edit of a property: BindingList cannot see inside an object. ItemDeleted index 0 carries the index the removed note had, which is why a grid can redraw the right row rather than all of them. The count of notes is one, and the first note is the second one added, because the first was removed.
Exercises
- Add a third note after the remove and run the program. What do the last two lines print?
- Replace the plain Note with one that raises PropertyChanged and run it; explain the extra event.
- Explain from the documentation what RaiseListChangedEvents = false does to a bound grid.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a BindingSource add to a list?
Answer
A position and a Current item, shared by the controls bound to it
A grid and a text box bound to one source stay on the same record.
-
Which property is the record a form is looking at?
Answer
Current, with Position as its index
PositionChanged and CurrentItemChanged report the move.
-
What does EndEdit() do?
Answer
Commits the edit a bound control is making
A Save button calls it before reading the item.
-
Which event does a BindingList raise when a row is added?
Answer
ListChanged with ItemAdded
There is one event; the ListChangedType says what happened.
-
Why does an edit of a property raise no event?
Answer
The list cannot see inside an object; the item must implement INotifyPropertyChanged
The run made four changes and saw three events.
-
What does ListChangedType.Reset mean?
Answer
The whole list changed, so a grid rebuilds every row
A sort is the usual cause.
-
What is the NewIndex of ItemDeleted?
Answer
The index the removed item had
The run printed ItemDeleted index 0 for the first note.
-
What did the run print for changes and events?
Answer
changes: 4, events: 3
The edit of the first note raised no event.
-
What does RaiseListChangedEvents = false do?
Answer
Suppresses the events during a bulk change
Put it back to true at the end, or the grid never hears again.
-
Which call binds a text box to a property of the current item?
Answer
DataBindings.Add(nameof(TextBox.Text), source, nameof(Note.Title), true)
The fourth argument enables formatting by the control's culture.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev