C# SplitContainer: Windows Forms

Use the SplitContainer control from Windows Forms to arrange controls in a window.

SplitContainer presents a resizable view. It splits the layout of your Windows Forms window into two parts: a left and right half, or a top and bottom half. It gives the user more control over how the window is arranged.

Start. To begin, take your Windows Forms application and add the SplitContainer control to it. Double-click on the SplitContainer icon in the Toolbox. By default, the SplitContainer has an orientation of vertical, indicating a vertical split.

Two panels. The SplitContainer will have two subcontainers in it. They can be accessed through the Panel1 and Panel2 properties. You can drag controls, such as a Button control or a TextBox control, to the two panels.

Tip: To make a control expand in the panel, please specify the Anchor property.

The Orientation property of the SplitContainer is useful. It allows you to change from vertical splitting to horizontal splitting. For the Horizontal setting, you can move the splitter up and down with the mouse.

Panel1, Panel2. You can add or remove controls, or change existing controls, by using the Panel1 and Panel2 properties in C# code. In this example, we enumerate all the controls in Panel1 and Panel2 for the program shown in the screenshots above.

Note: The results indicate that a Button instance is found in Panel1 and a TextBox instance is found in Panel2.

Example that uses Panel1 and Panel2 on SplitContainer: C# using System; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Get information about Panel1 controls and Panel2 controls. StringBuilder builder = new StringBuilder(); foreach (var control in splitContainer1.Panel1.Controls) { builder.Append("Panel1: ").AppendLine(control.GetType().ToString()); } foreach (var control in splitContainer1.Panel2.Controls) { builder.Append("Panel2: ").AppendLine(control.GetType().ToString()); } MessageBox.Show(builder.ToString()); } } } Output Panel1: System.Windows.Forms.Button Panel2: System.Windows.Forms.TextBox

SplitterMoved. One useful event handler on the SplitContainer control is the SplitterMoved event handler. This is triggered when the move has already occurred, not when it starts or is happening.

Tip: If you have to readjust parts of your program, or want to persist the position of the Splitter to disk, listen for this event.

Summary. The SplitContainer control is a container widget that presents a resizable, divided view to the user. It can have a vertical or horizontal split, and it has two properties Panel1 and Panel2 that can contain collections of sub-controls.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to