This lesson describes how to add and configure container controls. You will learn how to add controls to a form or to a container control and to configure various kinds of container controls to create dynamic and varied layouts for controls in your form.
After this lesson, you will be able to:
■ Add a control to a form or container control at design time.
■ Add a control to a form or container at run time.
■ Group and arrange controls with the Panel control.
■ Group and arrange controls with the GroupBox control.
■ Group and arrange controls with the TabControl control.
■ Group and arrange controls with the FlowLayoutPanel control.
■ Group and arrange controls with the TableLayoutPanel control.
■ Create dynamic container areas with the SplitContainer control.
Estimated lesson time: 45 minutes
Overview of Container Controls
Container controls are specialized controls that serve as a customizable container for other controls. Examples of container controls include the Panel, FlowLayoutPanel, and SplitContainer controls. Container controls give the form logical and physical sub
divisions that can group other controls into consistent user interface subunits. For example, you might contain a set of related RadioButton controls in a GroupBox con
trol. The use of container controls helps create a sense of style or information flow in your user interface and allows you to manipulate contained controls in a consistent fashion.
When a container control holds other controls, changes to the properties of the con
tainer control can affect the contained controls. For example, if the Enabled property of a panel is set to False, all of the controls contained within the panel are disabled.
Likewise, changes to properties related to the user interface, such as BackColor, Visible, or Font, are also applied to the contained controls. Note that you can still manually change any property inside a contained control, but if the container is disabled, all controls inside that container will be inaccessible regardless of their individual prop
erty settings.
The Controls Collection
Each form and container control has a property called Controls, which represents the collection of controls contained by that form or control. When a control is added to a form or container control at design time, the Designer automatically adds it to the controls collection of that form or container control and sets the location property as appropriate. You can also dynamically add a new control at run time by manually cre
ating a new control and adding the control to the controls collection.
To Add a Control to a Form or Container Control in the Designer
There are four ways to add a control to a form or container control in the Designer:
■ Drag the control from the Toolbox to the surface of the form or container control.
■ Select a control in the Toolbox, and then draw it on the form with the mouse.
■ Select a control in the Toolbox and double-click the form.
■ Double-click the control in the Toolbox.
To Add a Control to a Form or Container Control at Run Time
To add a control to a form or container control at run time, manually instantiate a new control and add it to the Controls collection of the form, as shown in the following example. You must set any properties of the control, such as the Location or Text prop
erties, before adding it to the controls collection. The following sample code assumes that you have added a Panel container named Panel1.
' VB
Dim aButton As New Button()
' Sets the relative location in the containing control or form aButton.Location = New Point(20,20)
aButton.Text = "Test Button"
' Adds the button to a panel called Panel1 Panel1.Controls.Add(aButton)
' Adds the button to a form called Form1 Me.Controls.Add(aButton)
// C#
Button aButton = new Button();
// Sets the relative location in the containing control or form aButton.Location = new Point(20,20);
aButton.Text = "Test Button";
// Adds the button to a panel called Panel1 Panel1.Controls.Add(aButton);
// Adds the button to a form called Form1 this.Controls.Add(aButton);
The Anchor Property
The Anchor and Dock properties of a control dictate how it behaves inside its form or parent control. The Anchor property allows you to define a constant distance between one or more edges of a control and one or more edges of a form or other container.
Thus, if a user resizes a form at run time, the control edges will always maintain a spe
cific distance from the edges. The default setting for the Anchor property is Top, Left, meaning that the top and left edges of the control always maintain a constant distance from the top and left edges of the form. If the Anchor property were set to Bottom, Right, for example, the control would “float” when the form was resized to maintain the constant distance between the bottom and right-hand edges of the form. If oppo
site properties are set for the Anchor property, such as Top and Bottom, the control will stretch to maintain the constant distance of the control edges to the form edges.
You can set the Anchor property to any combination of Top, Bottom, Left, Right, or none of these. In the Properties window, you are presented with a visual interface that aids in choosing the value for the Anchor property. This interface is shown in Figure 1-6.
Figure 1-6 Choosing the Anchor property
The Dock Property
The Dock property enables you to attach your control to the edge of a parent control.
The parent control can be a form or a container control such as a Panel control or a TabControl control.
Like the Anchor property, the Dock property provides a special visual interface that allows you to graphically choose the property value. This interface is shown in Figure 1-7.
Figure 1-7 Choosing the Dock property
To set the Dock property, click the section of the interface that corresponds to where you want your control to dock. For example, to dock your control to the right-hand side of the form, click the bar on the right of the interface. To release docking, choose None. Clicking the center of the Dock property interface sets the Dock property to a value of Fill, which means the the control will dock to all four sides of the form and fill the control in which it resides.
The GroupBox Control
The GroupBox control is a container control that appears as a subdivision of the form surrounded by a border. It does not provide scrollbars, like the Panel control, nor does it provide any kind of specialized layout capabilities. A GroupBox can have a caption, which is set by the Text property, or it can appear without a caption when the Text property is set to an empty string.
The most common use for GroupBox controls is for grouping RadioButton controls.
RadioButton controls placed within a single GroupBox are mutually exclusive but are not exclusive of other RadioButtons in the form or other GroupBox controls.
RadioButtons will be discussed in greater detail in Chapter 3, “Advanced Windows
Forms Controls.” Table 1-4 describes Text, the most important unique property of the GroupBox control.
Table 1-4 The Text Property of the GroupBox Control Property Description
Text Represents the caption of the GroupBox enclosure. If no cap
tion is desired, this property should be set to an empty string.
The Panel Control
The Panel control creates a subsection of a form that can host other controls. The Panel can be indistinguishable from the rest of the surrounding form, or it can be sur
rounded by a border as determined by the BorderStyle property. A Panel can have a BorderStyle property of None, which indicates no border; FixedSingle, which indicates a single edge around the Panel; or Fixed3D, which represents a border with a three- dimensional appearance.
The Panel control is a scrollable control, which means that it supports horizontal and vertical scroll bars. Controls can be hosted in the Panel outside of its visible bounds.
When the AutoScroll property is set to True, scroll bars will automatically be available if any controls are placed outside of the visible bounds of the control. If the AutoScroll property is set to False, controls outside the visible bounds of the panel are inaccessi
ble. Important properties of the Panel control are shown in Table 1-5.
Table 1-5 Important Properties of the Panel Control
Property Description
AutoScroll Determines if the Panel will display scroll bars when controls are hosted outside the visible bounds of the Panel. Scroll bars are displayed when this property is set to True and are not dis
played when it is set to False.
BorderStyle Represents the visual appearance of the Panel border. This property can be set to None, which indicates no border;
FixedSingle, which creates a single-line border; or Fixed3D, which creates a border with a three-dimensional appearance.
The FlowLayoutPanel Control
The FlowLayoutPanel is a subclass of the Panel control. Like the Panel control, it is most commonly used to create a distinct subsection of the form that hosts related controls.
Unlike the Panel control, however, the FlowLayoutPanel dynamically repositions the controls it hosts when it is resized at either design time or run time. This provides a great aid to user interface design because control positions are automatically adjusted as the size and dimensions of the FlowLayoutPanel are adjusted, and it provides dynamic realignment of the user interface (much like an HTML page) if the FlowLayoutPanel is resized at run time.
Like the Panel control, the FlowLayoutPanel control is a scrollable control. Scroll bars are enabled when AutoScroll is set to True and are disabled when AutoScroll is set to False.
The default flow direction of the FlowLayoutPanel is from left to right, meaning that controls placed in the FlowLayoutPanel will locate in the upper left-hand corner and then flow to the right until they reach the edge of the panel. This behavior is con
trolled by the FlowDirection property. The FlowDirection property can be set to four possible values: LeftToRight, which is the default; RightToLeft, which provides flow from right to left; TopDown, in which the controls flow from the top of the control to the bottom; and BottomUp, in which controls flow from the bottom to the top of the FlowLayoutPanel.
Once the end of a row (in the case of LeftToRight and RightToLeft FlowDirections) or column (in the case of TopDown and BottomUp FlowDirections) is reached, the flow will wrap or not wrap to the next row or column as determined by the value of the WrapContents property. If WrapContents is set to True (which is the default), controls will automatically wrap to the next column or row. If set to False, controls will not automatically form new rows or columns.
You can manually create breaks in the flow of the controls that are analogous to line breaks in text. When the WrapContents property of a FlowLayoutPanel control is set to False, you must manually set flow breaks to manage the flow, but you can also set flow breaks when WrapContents is set to True if you desire individual breaks. You can set a flow break on a control by calling the SetFlowBreak method of the FlowLayoutPanel.
� To set a flow break on a control hosted in a FlowLayoutPanel
1. Set the flow break by using the SetFlowBreak method as shown in the following example (which assumes a FlowLayoutPanel control named Flp and a Button named aButton have already been created):
' VB
Flp.SetFlowBreak(aButton, True)
// C#
Flp.SetFlowBreak(aButton, true);
2. Regardless of whether there is room in the FlowLayoutPanel to continue the flow of controls, a control that has had a flow break set by this method will start a new row (or column, depending on the value of the FlowDirection property) in the FlowLayoutPanel.
3. You can query a particular control to determine if it has had a flow break set for it by calling the GetFlowBreak method as shown in the following example:
' VB
If Flp.GetFlowBreak(aButton) Then ' Continue processing
End If
// C#
if (Flp.GetFlowBreak(aButton)) { // Continue processing }
Table 1-6 lists important properties and methods of the FlowLayoutPanel control.
Table 1-6 Important Members of the FlowLayoutPanel Control
Property/Method Description
AutoScroll Property. Determines if the FlowLayoutPanel will display scroll bars when controls are hosted out
side the visible bounds of the Panel. Scroll bars are displayed when set to True and are not displayed when set to False.
BorderStyle Property. Represents the visual appearance of the Panel border. It can be set to None, which indicates no border; FixedSingle, which creates a single-line border; or Fixed3D which creates a border with a three-dimensional appearance.
Table 1-6 Important Members of the FlowLayoutPanel Control Property/Method Description
FlowDirection Property. Determines the direction of flow in the FlowLayoutPanel. Can be set to LeftToRight, Right- ToLeft, TopBottom, or BottomUp.
WrapContents Property. Determines whether controls will auto
matically wrap to the next column or row when the FlowLayoutPanel is resized.
GetFlowBreak Method. This method returns a Boolean value that indicates whether a particular control has had a flow break set.
SetFlowBreak Method. This method sets a flow break on a con
trol contained in the FlowLayoutPanel.
The TableLayoutPanel Control
Like the FlowLayoutPanel control, the TableLayoutPanel control is a specialized panel that aids in the design and layout of the user interface. The TableLayoutPanel is essen
tially a table that provides cells for the individual hosting of controls. Like other pan
els, it is a scrollable container that provides scroll bars when the AutoScroll property is set to True.
At design time, the TableLayoutPanel appears on the form as a table of individual cells.
You can drag controls from the Toolbox into each of the cells. Generally, only one con
trol can be hosted in a single cell although, for complicated user interface designs, you can nest other container controls inside TableLayoutPanel cells, each of which can host multiple controls.
At run time, the appearance of the cells is determined by the CellBorderStyle property.
This property can be set to None, which displays no cell lines, or to Single, Inset, Inset- Double, Outset, OutsetDouble, or OutsetPartial, each of which provides a distinctive look and feel to the table cells.
The columns and rows of the TableLayoutPanel control are managed by the ColumnStyle and RowStyle collections. At design time, you can set the styles of the rows and columns by choosing the ColumnStyles or RowStyles collection in the Property Grid and launch
ing the Columns And Rows Styles editor, shown in Figure 1-8.
Figure 1-8 The Columns and Rows Styles editor
You can alter column and row size styles with this editor. Column and row styles can be set to Absolute, which indicates a fixed size in pixels, or they can be set to Relative, which indicates a percentage of the size of all columns or rows whose style is set to Relative. Columns and rows can also be set to AutoSize. When set to this value, the col
umns and rows will automatically adjust to the correct size.
Column and row styles can also be set manually in code by accessing the ColumnStyles and RowStyles collections in code. You can access the style for a particular column or row by the index of that column or row. Styles can be set as shown in the following example:
' VB
TableLayoutPanel1.ColumnStyles(0).SizeType = SizeType.Absolute TableLayoutPanel1.ColumnStyles(0).Width = 20
TableLayoutPanel1.RowStyles(0).SizeType = SizeType.Percent TableLayoutPanel1.RowStyles(0).Height = 50
// C#
TableLayoutPanel1.ColumnStyles[0].SizeType = SizeType.Absolute;
TableLayoutPanel1.ColumnStyles[0].Width = 20;
TableLayoutPanel1.RowStyles[0].SizeType = SizeType.Percent;
TableLayoutPanel1.RowStyles[0].Height = 50;
If you set a row or column style to a size type of anything other than SizeType.Absolute, you can also set the Width (for columns) or Height (for rows). These values are set in either pixels or percentages as is appropriate for the SizeType of the ColumnStyle.
When adding new controls to a TableLayoutPanel at run time, you can use either of two overloads of the TableLayoutPanel.Controls.Add method. The first is the standard Add method, as follows:
' VB
TableLayoutPanel1.Controls.Add(aButton)
// C#
TableLayoutPanel1.Controls.Add(aButton);
This method simply adds the control to the controls collection of the TableLayoutPanel, and the control is inserted into the next open cell in the table. If there are no more open cells, the behavior of the TableLayoutPanel is determined by the value of the GrowStyle property. If the GrowStyle property is set to AddRows, additional rows will be added to accommodate new controls. If the GrowStyle property is set to AddColumns, new col
umns will be added when needed. If the GrowStyle property is set to FixedSize, no new cells may be added. If you attempt to add a control to a TableLayoutPanel with a GrowStyle value of FixedSize, an exception will be thrown.
You can also add a control to a specific cell by using the Controls.Add method, as follows:
' VB
TableLayoutPanel1.Controls.Add(aButton,3,3)
// C#
TableLayoutPanel1.Controls.Add(aButton,3,3);
Columns in a TableLayoutPanel are numbers starting at 1, while rows start at 0. Thus, the example shown above adds aButton to the cell in column 3 at row 3, which is actu
ally the 3rd column and the 4th row the user sees. Note, however, that if a cell is already occupied by a control, your control might not be added to that cell. Controls added to cells at design time generally have precedence over controls added at run time. In these cases, the control is simply added to the next available cell. If you add the control to a cell that contains another control that has been added at run time, the cell already in that position will usually be moved down to the next available cell in favor of the control just added. As always, careful testing is important.
� To add a control to a TableLayoutPanel control at run time 1. Declare and instantiate a new control in code.
2. Use the TableLayoutPanel.Controls.Add method to add the control. An example follows:
' VB
Dim aButton As New Button()
' Adds the Button to the next available cell TableLayoutPanel1.Controls.Add(aButton) ' Adds the Button to a cell at (2,2)
TableLayoutPanel1.Controls.Add(aButton, 2, 2)
// C#
Button aButton = new Button();
// Adds the Button to the next available cell TableLayoutPanel1.Controls.Add(aButton);
// Adds the Button to a cell at (2,2)
TableLayoutPanel1.Controls.Add(aButton, 2, 2);
Table 1-7 lists important properties and methods of the TableLayoutPanel control.
Table 1-7 Important Members of the TableLayoutPanel Control Property/Method Description
AutoScroll Property. Determines if the TableLayoutPanel will display scroll bars when controls are hosted out
side the visible bounds of the Panel. Scroll bars are displayed when this property is set to True and are not displayed when it is set to False.
CellBorderStyle Property. Determines the style of the cell borders.
This property can be set to None, which indicates no cell borders, or to a variety of different visual styles.
ColumnCount Property. Indicates the number of columns. You can add or remove columns by incrementing or decrementing the ColumnCount property.
Columns Property. Represents the collection of columns.
Available only at design time; accessing this prop
erty launches the Columns And Rows Styles editor.
ColumnStyles Property. Represents the collection of column styles. Available only at run time.