Add a Splitter to a WinForm
By Fons Sonnemans (April 2002)
Download
SplitterDemo.zip
Introduction
I used to program in Visual Basic 6.0. It is a great tool but not perfect.
It was lacking some crucial controls. A Splitter control was one of them. Microsoft
has added it to the .NET framework (thanks) but forgot to make it easy to use. You
must place it on a Form, set some properties for it and then also some (Dock)
properties of the other two controls. Then you have to set the order of the controls
correctly by using 'Bring to Front' or 'Send to Back'.
This article demonstrates the use of a simple AddSplitter() method which simplifies
the use of splitters.
AddSplitter() method
public static Splitter
AddSplitter(Control control1, Control control2, bool
vertical)
{
Control parent
= control1.Parent;
if
(parent != control2.Parent)
throw
new ArgumentException(
"Both controls must be placed on the same Containter");
if (parent.Controls.Count
> 2)
throw
new ArgumentException(
"There may only be 2 controls on the Container");
parent.SuspendLayout();
if
(parent.Controls.IndexOf(control2) > parent.Controls.IndexOf(control1))
parent.Controls.SetChildIndex(control2,
0);
Splitter splitter
= new Splitter();
splitter.Dock
= System.Windows.Forms.DockStyle.Left;
control2.Dock
= DockStyle.Fill;
if (vertical)
{
control1.Dock = DockStyle.Left;
splitter.Dock = DockStyle.Left;
splitter.Width =
6;
}
else
{
control1.Dock = DockStyle.Top;
splitter.Dock = DockStyle.Top;
splitter.Height =
6;
splitter.Cursor = Cursors.HSplit;
}
parent.Controls.Add(splitter);
parent.Controls.SetChildIndex(splitter,1);
parent.ResumeLayout();
return
splitter;
}
Usage
I will explain how you can create a Form with two Spitters as shown above. Create
a Windows Form and a a ListBox and a Panel to it. Add another ListBox and TextBox
and place them in the Panel.
Do not place any Spliters on the Form, they will be added using the AddSplitter()
method. Modify the constructor of the Form.
public FormBoth()
{
InitializeComponent();
ControlUtil.AddSplitter(listBox1,
panel1,
true);
ControlUtil.AddSplitter(listBox2,
textBox1, false);
}
The vertical splitter is added between Listbox1 and the panel. The horizontal
splitter is added between ListBox2 and TextBox1.
Conclusion
Splitters are great but not easy to use, the AddSplitter() method solves this.
Any suggestions and feedback for improving this article is most welcome. Send your
suggestions and feedback to Fons.Sonnemans@reflectionit.nl