Panel and the Controls collection

A Panel is the plainest container in WinForms: a rectangle that holds controls. It draws no caption and no frame unless it is asked, and its reason to exist is the collection every container has, Controls. That collection is how a form is a tree, and the tree is how a layout, a tab order and a search for a control by name all work.

Panel

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 = "A side panel"; ClientSize = new Size(520, 320); var side = new Panel { Dock = DockStyle.Left, Width = 180, BorderStyle = BorderStyle.FixedSingle, AutoScroll = true, Padding = new Padding(8), }; var list = new ListBox { Dock = DockStyle.Top, Height = 120 }; list.Items.AddRange(new object[] { "Inbox", "Sent", "Drafts" }); var buttons = new Panel { Dock = DockStyle.Bottom, Height = 40 }; var add = new Button { Text = "&Add", Dock = DockStyle.Left, Width = 80 }; var remove = new Button { Text = "&Remove", Dock = DockStyle.Right, Width = 90 }; buttons.Controls.Add(remove); buttons.Controls.Add(add); side.Controls.Add(list); side.Controls.Add(buttons); var editor = new RichTextBox { Dock = DockStyle.Fill }; Controls.Add(editor); Controls.Add(side); } }

dotnet build app.csproj

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

The listing is built and not run. The panel docks to the left and takes 180 pixels; its Padding moves the two children eight pixels in from its frame; AutoScroll adds scroll bars when the children are larger than the visible area, which is what a panel with a list of unknown length needs. The inner buttons panel is a container inside a container, and it is where the two buttons live so that they stay at the bottom of the side panel whatever the list does.

The Controls collection

Every container exposes its children as a Control.ControlCollection: an ordered collection with an indexer by number and by Name.

using System; using System.Drawing; using System.Linq; using System.Windows.Forms; internal sealed class Form1 : Form { public Form1() { Text = "Walking the form"; ClientSize = new Size(420, 220); var group = new GroupBox { Text = "Contact", Location = new Point(16, 16), Size = new Size(380, 120) }; group.Controls.Add(new TextBox { Name = "nameBox", Location = new Point(16, 28), Width = 300 }); group.Controls.Add(new TextBox { Name = "emailBox", Location = new Point(16, 64), Width = 300 }); Controls.Add(group); var fields = Controls["groupBox1"]; var name = group.Controls["nameBox"] as TextBox; var boxes = group.Controls.OfType<TextBox>().ToList(); Console.WriteLine($"found: {fields?.Name}, {name?.Name}, {boxes.Count} boxes"); } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it, and one line of it would not compile anyway: the group box was created without a Name, so Controls["groupBox1"] finds nothing and returns null. The indexer searches the immediate children only, by Name, and it does not walk into a child's own collection. A search of a whole form is a loop:

One rule bites everyone once: a control has exactly one parent. Adding it to a second container removes it from the first, without an exception and without a word, so a control that vanishes from a form was probably added twice.

Parent and z-order

The order of Controls is the z-order: index 0 is the control in front, the last index is the one at the back. Three methods move a control within it, and each changes what the user sees and what a docked layout does:

The designer adds the controls in the reverse of the order it draws them, which is why its Controls.Add lines look upside down in InitializeComponent. A form written by hand is free of that and only has to be right about it where docking is involved.

A control tree that runs

A form is a tree, and the walk over it is the same recursion whatever the controls are. This program builds a small tree and prints it with its depth, and it runs here:

using System; using System.Collections.Generic; using System.Linq; var form = new Node("Form1"); var group = new Node("groupContact"); group.Children.Add(new Node("nameBox")); group.Children.Add(new Node("emailBox")); var panel = new Node("panelSide"); panel.Children.Add(new Node("treeFiles")); form.Children.Add(group); form.Children.Add(panel); form.Walk(0); Console.WriteLine($"nodes: {form.Count()}"); internal sealed class Node { public Node(string name) => Name = name; public string Name { get; } public List<Node> Children { get; } = new(); public void Walk(int depth) { Console.WriteLine($"{new string(' ', depth * 2)}{Name}"); foreach (var child in Children) { child.Walk(depth + 1); } } public int Count() => 1 + Children.Sum(child => child.Count()); }

dotnet run

Form1
  groupContact
    nameBox
    emailBox
  panelSide
    treeFiles
nodes: 6

The output is the real run. The recursion is the same one a form needs for "clear every text box", "find the control called codeBox" or "validate every child", and the count is the reason to write it once rather than three times. On a real form the type is Control and the children are control.Controls; the shape is identical.

One warning about the real collection: a loop that removes children while it enumerates Controls throws InvalidOperationException, because the collection changed under the enumerator. The fix is a snapshot, Controls.Cast<Control>().ToArray(), and then a loop over the array.

Exercises

  1. Add a third level to the tree, print it and work out the count before running the program.
  2. Write a Walk that prints the node count of each child after its name, and run it.
  3. Explain why removing a control inside a foreach over Controls throws, and write the snapshot version.

Questions

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

  1. What does Controls["name"] search?

    Answer

    The immediate children, by their Name property

    The indexer is the immediate collection only; a whole-form search is a walk.

  2. What is index 0 of a Controls collection?

    Answer

    The control in front, the top of the z-order

    The collection order is the z-order, not the tab order.

  3. What happens when a control is added to a second container?

    Answer

    It is removed from the first, because it has one parent

    Parent is single, so the add is a reparent.

  4. What does BringToFront() do?

    Answer

    Moves the control to index 0 of its parent's collection

    It changes the z-order, which the layout and the drawing both follow.

  5. Which property of a panel adds scroll bars for content that does not fit?

    Answer

    AutoScroll

    AutoSize grows the panel; AutoScroll scrolls it.

  6. What does Panel.Padding do?

    Answer

    Holds its children away from its edges

    Padding is inside the container, Margin is outside the control.

  7. Why does a loop that removes children inside foreach over Controls throw?

    Answer

    The collection changes while the enumerator is running

    The fix is a snapshot array, then a loop over it.

  8. What did the run print as the node count?

    Answer

    6

    The form, two containers and three fields.

  9. Which line prints the tree with its depth?

    Answer

    new string(' ', depth * 2) in the Walk method

    The recursion passes depth + 1 and indents by twice it.

  10. When is a Panel better than a GroupBox?

    Answer

    When the group needs no caption or a different background

    Both group radio buttons; the panel adds no caption and can scroll.

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