ListBox and CheckedListBox
A ListBox shows a list of items and lets the user pick one or several. A CheckedListBox shows the same list with a check box per row, which is the control for "any number of these", where a list box with MultiExtended is the control for "these, selected together". The difference looks cosmetic and is not: a selection is a temporary highlight, a check is a value.
ListBox
using System;
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 ListBox _files = new()
{
Location = new Point(16, 16),
Size = new Size(240, 150),
SelectionMode = SelectionMode.MultiExtended,
IntegralHeight = false,
};
private readonly Label _status = new() { Location = new Point(16, 180), AutoSize = true };
public Form1()
{
Text = "Files";
ClientSize = new Size(360, 220);
_files.Items.AddRange(new object[] { "notes.txt", "ideas.txt", "todo.txt", "archive.txt" });
_files.SelectedIndexChanged += Describe;
Controls.Add(_files);
Controls.Add(_status);
}
private void Describe(object? sender, EventArgs e)
{
var names = new System.Text.StringBuilder();
foreach (var item in _files.SelectedItems)
{
if (names.Length > 0)
{
names.Append(", ");
}
names.Append(item);
}
_status.Text = $"{_files.SelectedItems.Count} selected: {names}";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. IntegralHeight = false lets the control show a partial row at the bottom instead of shrinking to a whole number of rows, which is what a fixed Size needs. The handler walks SelectedItems, which for a multi-selection mode is the only reliable source: SelectedIndex is the first of them, not all of them.
Selection modes
- SelectionMode.One: one row at a time, which is the default and what a single SelectedIndex means.
- SelectionMode.MultiSimple: a click toggles a row, with no modifier key.
- SelectionMode.MultiExtended: Ctrl+click toggles, Shift+click extends, exactly as Explorer behaves. The mode a user expects when the list is a set of files.
- SelectionMode.None: nothing can be selected. It is right for a list that only displays, and the rows still scroll and still take the focus.
The items are objects, as in a combo box, and the visible text is ToString() unless DisplayMember asks otherwise. Items is an ordinary collection: Add, AddRange, Remove, Clear, IndexOf, and an indexer that reads an item by position. A list that changes while the user works is bound to a BindingList<T> instead of filled once, which is lesson 044.
CheckedListBox
using System;
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 CheckedListBox _columns = new()
{
Location = new Point(16, 16),
Size = new Size(220, 130),
CheckOnClick = true,
};
private readonly Label _status = new() { Location = new Point(16, 160), AutoSize = true };
public Form1()
{
Text = "Columns";
ClientSize = new Size(340, 200);
_columns.Items.Add("Date", true);
_columns.Items.Add("Customer", true);
_columns.Items.Add("Total", false);
_columns.Items.Add("Notes", false);
_columns.ItemCheck += OnItemCheck;
Controls.Add(_columns);
Controls.Add(_status);
ShowChecked();
}
private void OnItemCheck(object? sender, ItemCheckEventArgs e)
{
var state = e.NewValue == CheckState.Checked ? "on" : "off";
_status.Text = $"item {e.Index} turns {state}";
}
private void ShowChecked()
{
var chosen = 0;
foreach (var item in _columns.CheckedItems)
{
chosen++;
}
_status.Text = $"{chosen} columns shown";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run, and one detail of it is the lesson. ItemCheck fires before the item changes, so CheckedItems inside the handler still holds the old state; the new state is e.NewValue. A handler that needs the state after the change reads e and counts, or queues the recount with BeginInvoke. CheckOnClick = true makes a single click toggle the box instead of selecting the row first, which is what a column chooser wants.
- CheckedIndices and CheckedItems: the checked rows, in the order they were checked.
- GetItemChecked(index), SetItemChecked(index, value) and GetItemCheckState(index): one row at a time, without a collection.
- ThreeDCheckBoxes and CheckOnClick: appearance and the click rule.
- Items.Add(item, isChecked): adds a row with its state in one call, as the listing does.
A summary that runs
What a form does with a selection is the application's own rule: which items were picked, in which order, and what to say when nothing was. That rule has no control in it, and it runs here:
using System;
using System.Collections.Generic;
using System.Linq;
var names = new[] { "Alpha", "Beta", "Gamma", "Delta" };
var selected = new[] { 0, 2 };
var checkedIndexes = new[] { 1, 3 };
Console.WriteLine($"selected: {Join(names, selected)}");
Console.WriteLine($"checked: {Join(names, checkedIndexes)}");
Console.WriteLine($"counts: {selected.Length} selected, {checkedIndexes.Length} checked");
static string Join(string[] items, int[] indexes)
{
var picked = indexes.Where(i => i >= 0 && i < items.Length).Select(i => items[i]);
var text = string.Join(", ", picked);
return text.Length == 0 ? "(none)" : text;
}
dotnet run
selected: Alpha, Gamma
checked: Beta, Delta
counts: 2 selected, 2 checked
The output is the real run. The guard i >= 0 && i < items.Length is not decoration: an index that came from a saved file can be out of range after the list changed, and a list control reports -1 for "nothing selected", which a caller will eventually pass on. The empty case returns (none) here so that the text says something; a form would disable its OK button instead.
Exercises
- Change the summary to keep the order of the check boxes rather than the order of checking, and run it.
- Add a fifth row to the checked list and make the status line count the checked ones with GetItemChecked.
- Explain why the ItemCheck handler cannot read CheckedItems for the new state, and write the two ways around it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which SelectionMode gives the Ctrl+click and Shift+click behaviour of Explorer?
Answer
MultiExtended
MultiExtended is the modifier-key mode; MultiSimple toggles on a plain click.
-
Which property holds every selected row of a multi-selection ListBox?
Answer
SelectedItems
SelectedIndex is only the first of them; SelectedItems is the collection.
-
What does CheckOnClick do on a CheckedListBox?
Answer
A single click toggles the check box instead of only selecting the row
It saves the user a second click, which is what a column chooser wants.
-
When does ItemCheck fire compared with the change of state?
Answer
Before the state changes, so CheckedItems is still the old state
The new state is in e.NewValue; the collection still holds the old one.
-
Which property of ItemCheckEventArgs holds the state the row is moving to?
Answer
NewValue
CurrentValue is the old state, NewValue the one that is about to apply.
-
Which call adds a row to a CheckedListBox already checked?
Answer
Items.Add(item, true)
Items.Add takes the initial check state as its second argument.
-
What does IntegralHeight = false change?
Answer
The list may show a partial row instead of shrinking to whole rows
With it true, the height snaps to a whole number of rows.
-
What does the headless summary print for selected = { 0, 2 }?
Answer
selected: Alpha, Gamma
The run printed the names at those indexes, joined with a comma.
-
Why does the summary guard the index with i < items.Length?
Answer
An index from a saved file can be out of range after the list changed
Indices are not stable data; the guard is what keeps a stale value from throwing.
-
When is a CheckedListBox the wrong control?
Answer
When the user must choose exactly one of the rows
Exactly one of several is a ListBox with SelectionMode.One, or radio buttons.
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