TabControl

A TabControl is a stack of pages with a row of tabs above them. It is the control for a settings dialog with four sections and for an editor with a document per tab, and the two uses are the same property set read at different moments: a settings dialog builds its pages once and never removes one, while an editor adds a page when a file opens and removes it when the file closes.

Pages behind tabs

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 { public Form1() { Text = "Settings"; ClientSize = new Size(460, 300); var tabs = new TabControl { Dock = DockStyle.Fill, Appearance = TabAppearance.Normal, Multiline = false, }; var general = new TabPage("General"); general.Controls.Add(new CheckBox { Text = "Open the last file at start-up", Location = new Point(16, 20), AutoSize = true, }); var editor = new TabPage("Editor"); editor.Controls.Add(new NumericUpDown { Location = new Point(16, 20), Maximum = 200, Value = 100, Width = 90, }); var about = new TabPage("About") { ToolTipText = "Version and licence" }; tabs.TabPages.Add(general); tabs.TabPages.Add(editor); tabs.TabPages.Add(about); tabs.SelectedIndex = 1; Controls.Add(tabs); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. A TabPage is a container, so its controls go into the page's own Controls, exactly as they would go into a panel. SelectedIndex = 1 opens the Editor page first, which is the line a settings dialog has after it restores the last page the user had open.

The selection

Three events follow a change of page, and the order is what makes the cancellation possible:

A page's controls are created when the page is created, not when it is first shown, so a page with an expensive grid is expensive at start-up. A form with ten heavy pages loads the data in Selected for the first visit and remembers that it did.

A page per document

The editor pattern is the same control with a page whose caption is a file name and whose content is an editor. The designer cannot help with it, because the pages do not exist at design time; the code adds one per file and removes it on close:

using System; using System.Drawing; using System.IO; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly TabControl _tabs = new() { Dock = DockStyle.Fill }; public Form1() { Text = "Documents"; ClientSize = new Size(560, 360); Controls.Add(_tabs); } public void Open(string path) { foreach (TabPage page in _tabs.TabPages) { if (page.Tag as string == path) { _tabs.SelectedTab = page; return; } } var editor = new RichTextBox { Dock = DockStyle.Fill, Text = File.ReadAllText(path) }; var tab = new TabPage(Path.GetFileName(path)) { Tag = path }; tab.Controls.Add(editor); _tabs.TabPages.Add(tab); _tabs.SelectedTab = tab; } public void CloseCurrent() { if (_tabs.SelectedTab is { } page) { _tabs.TabPages.Remove(page); } } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. Two details are worth keeping. The Tag of the page holds the full path, because the caption is only the file name and two folders can hold the same name. And opening a file that is already open selects its tab instead of adding a second one, which is the loop at the top.

A close button on the tab itself needs owner drawing or a small custom control: a TabControl draws its tabs and offers no TabPage.CloseButton. The usual answer is a middle-click handler, a context menu, or the DrawMode.OwnerDrawFixed route of lesson 065.

A tab strip that runs

The rule behind those tabs is a list, a selected value and what happens when the selected item is removed. That rule runs here:

using System; using System.Collections.Generic; var tabs = new TabStrip(); tabs.Open("notes.txt"); tabs.Open("ideas.txt"); tabs.Open("notes.txt"); tabs.Select("ideas.txt"); Console.WriteLine($"selected: {tabs.Selected}"); Console.WriteLine($"close ideas.txt: {tabs.Close("ideas.txt")}"); Console.WriteLine($"selected after close: {tabs.Selected ?? "(none)"}"); Console.WriteLine($"count: {tabs.Count}"); internal sealed class TabStrip { private readonly List<string> _tabs = new(); public string? Selected { get; private set; } public int Count => _tabs.Count; public void Open(string name) { if (!_tabs.Contains(name)) { _tabs.Add(name); } Selected = name; } public void Select(string name) { if (!_tabs.Contains(name)) { throw new InvalidOperationException(name); } Selected = name; } public bool Close(string name) { var index = _tabs.IndexOf(name); if (index < 0) { return false; } _tabs.RemoveAt(index); if (Selected == name) { Selected = _tabs.Count == 0 ? null : _tabs[Math.Max(0, index - 1)]; } return true; } }

dotnet run

selected: ideas.txt
close ideas.txt: True
selected after close: notes.txt
count: 1

The output is the real run. Opening a file that is already there selects it instead of adding a second tab, which is what the third call proves. Closing the selected tab moves the selection to the tab before it, and the guard for the last tab leaves nothing selected, which in a TabControl is SelectedIndex = -1. The real control does not choose the next tab by itself when a page is removed, so this is the rule the form has to write.

Exercises

  1. Make Close select the next tab instead of the previous one, and run the program.
  2. Add a CloseAll method and print the selection after it.
  3. Explain from the documentation what Deselecting does when e.Cancel is set.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which property is the page that is showing?

    Answer

    SelectedTab, or SelectedIndex by number

    SelectedTab is the object; SelectedIndex is its position, or -1.

  2. Where do the controls of a TabPage live?

    Answer

    In the page's own Controls collection

    A TabPage is a container, like a panel with a caption.

  3. Which event can cancel a change of page?

    Answer

    Deselecting, with e.Cancel

    It fires on the page being left, before the change.

  4. When are the controls of a TabPage created?

    Answer

    When the page is created, not when it is first shown

    That is why a heavy page costs at start-up and loads its data in Selected.

  5. What does Appearance = Buttons do?

    Answer

    Draws the tabs as a row of buttons

    FlatButtons is the flat variant; Alignment moves the row.

  6. What does Multiline = true do?

    Answer

    Adds a second row of tabs instead of scrolling arrows

    Only one page shows at a time in any configuration.

  7. How does the editor pattern keep the full path of a document?

    Answer

    In the Tag of its TabPage

    The caption shows the file name only, and two folders can hold the same name.

  8. What did the run print for the third Open of notes.txt?

    Answer

    Nothing new: it selected the existing tab, so the count stayed 2 until a close

    The Open method selects an existing tab instead of adding a duplicate.

  9. What happens to SelectedIndex when the last page is removed?

    Answer

    It becomes -1

    The control does not choose a page by itself.

  10. Why does a close button on the tab need owner drawing?

    Answer

    A TabControl draws its own tabs and has no per-tab button

    The other routes are a middle click or a context menu.

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