ComboBox
A ComboBox is a text box with a list behind it. It is the control for a choice among a dozen values, where a group of radio buttons takes too much room and a list box is too tall. The list is an ObjectCollection: it holds any object, and what the user sees is that object's ToString() unless a display member says otherwise.
A box with a list behind it
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 ComboBox _period = new()
{
Location = new Point(16, 16),
Width = 160,
DropDownStyle = ComboBoxStyle.DropDownList,
};
private readonly Label _result = new() { Location = new Point(16, 60), AutoSize = true };
public Form1()
{
Text = "Period";
ClientSize = new Size(360, 110);
_period.Items.AddRange(new object[] { "Day", "Week", "Month", "Quarter" });
_period.SelectedIndex = 1;
_period.SelectedIndexChanged += OnPeriodChanged;
Controls.Add(_period);
Controls.Add(_result);
OnPeriodChanged(this, EventArgs.Empty);
}
private void OnPeriodChanged(object? sender, EventArgs e)
{
_result.Text = $"selected: {_period.SelectedItem} at index {_period.SelectedIndex}";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. Items.AddRange fills the list with four strings, SelectedIndex = 1 chooses Week, and SelectedIndexChanged runs once for that assignment and once for every choice the user makes. The event handler reads SelectedItem, the object, and SelectedIndex, its position.
The three styles
- DropDownStyle.DropDown (the default): the text can be typed, and the list is a suggestion. The user can enter a value that is not in the list, which is either the feature or the bug, depending on the form.
- DropDownStyle.DropDownList: the text cannot be typed, only chosen. This is the one a form with a fixed set of values wants, because it makes an invalid value impossible instead of validating it afterwards.
- DropDownStyle.Simple: the list is always open below the box. It is a list box with a text field, and rarely the right choice.
With DropDownList the empty state matters: a combo with no selection has SelectedIndex == -1 and SelectedItem == null. A form that must start with a value sets SelectedIndex in its constructor; a form that must start empty leaves it and handles the null in the handler, which is what Nullable is for.
What is selected
Four properties describe the selection, and they answer different questions:
- SelectedIndex: the position in the list, or -1 for nothing.
- SelectedItem: the object at that position, typed as object?. A cast gives the real type back.
- Text: what the box shows. With DropDownList it is the display text of the selected item; with DropDown it is whatever the user typed.
- SelectedValue: the value of the property named by ValueMember, once the combo is data-bound. Lesson 048, about data binding, comes back to it.
The list can hold objects instead of strings, and then DisplayMember and ValueMember decide what the user sees and what the code reads:
using System;
using System.Drawing;
using System.Windows.Forms;
internal sealed record Period(string Name, int Days);
internal sealed class Form1 : Form
{
private readonly ComboBox _period = new()
{
Location = new Point(16, 16),
Width = 180,
DropDownStyle = ComboBoxStyle.DropDownList,
DisplayMember = nameof(Period.Name),
ValueMember = nameof(Period.Days),
};
public Form1()
{
Text = "A list of objects";
ClientSize = new Size(360, 100);
_period.Items.Add(new Period("Day", 1));
_period.Items.Add(new Period("Week", 7));
_period.Items.Add(new Period("Month", 30));
_period.SelectedIndex = 1;
var chosen = (Period)_period.SelectedItem!;
_period.Text = chosen.Name;
Controls.Add(_period);
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. Reading the selection as (Period)SelectedItem is direct and needs the cast; a data-bound combo reads SelectedValue instead and avoids it.
The mapping that runs
The interesting part of a period combo is not the control, it is the table behind it: a display name, a number of days, and a lookup that answers null for a name that is not there. That is plain code, and it runs here:
using System;
using System.Collections.Generic;
using System.Linq;
var choices = PeriodChoice.All;
var selected = choices[1];
foreach (var choice in choices)
{
Console.WriteLine($"{choice.Name,-8} {choice.Days,3} days");
}
Console.WriteLine($"selected: {selected.Name} -> {selected.Days} days");
foreach (var name in new[] { "Week", "Year" })
{
var match = choices.FirstOrDefault(c => c.Name == name);
Console.WriteLine($"{name}: {(match is null ? "no such period" : $"{match.Days} days")}");
}
internal sealed record PeriodChoice(string Name, int Days)
{
public static IReadOnlyList<PeriodChoice> All { get; } = new[]
{
new PeriodChoice("Day", 1),
new PeriodChoice("Week", 7),
new PeriodChoice("Month", 30),
new PeriodChoice("Quarter", 91),
};
}
dotnet run
Day 1 days
Week 7 days
Month 30 days
Quarter 91 days
selected: Week -> 7 days
Week: 7 days
Year: no such period
The output is the real run of that program. It is the table a combo box would show, with the two questions a form asks of it: what is selected, and what does a name that came from somewhere else mean. The second question is why the lookup returns null rather than throwing: a name from a settings file or a saved document may be one the current version no longer has.
Exercises
- Add a fifth period to the table and print it, then run the program again.
- Change DropDownStyle to DropDown and explain which invalid input the form must now validate.
- Bind the combo to PeriodChoice.All with DisplayMember and read SelectedValue.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which DropDownStyle stops the user from typing a value that is not in the list?
Answer
DropDownList
DropDownList turns the text field into a display of the selection.
-
What is SelectedIndex when nothing is selected?
Answer
-1
The convention is -1 for no selection, and SelectedItem is null.
-
What is SelectedItem?
Answer
The object at the selected position, typed as object
A cast gives the real type back; Text is the display string.
-
Which event fires when the user chooses another item?
Answer
SelectedIndexChanged
It fires for the user's choice and for a programmatic assignment of SelectedIndex.
-
What do DisplayMember and ValueMember do on a combo with objects?
Answer
Choose the property shown and the property read as the value
They let the list hold full objects while the box shows one property.
-
What does Items.AddRange take?
Answer
An array of objects
The collection holds objects; the display text comes from ToString or DisplayMember.
-
Why does the mapping print no such period for Year?
Answer
FirstOrDefault returns null for a name that is not in the table
The lookup is by display name, and Year is not one of the four choices.
-
Which output line did the run print for Week?
Answer
Week: 7 days
The lookup line for Week printed Week: 7 days; the selected line is a different line of output.
-
When is a combo box a better choice than radio buttons?
Answer
When the list is long enough that the buttons would take too much room
A dozen values is a list; two or three are buttons the user sees at once.
-
What does a record give the PeriodChoice type here?
Answer
A constructor, value equality and a readable ToString in one line
A positional record is the shortest way to a small value type with a name and a number.
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