Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

C# Panel Container Control Explained

1. Introduction

The Panel Container Control is all about this article. We will see how to use the panel control for grouping the controls. Then we will explore the important properties of this container along with an example.

Panel Container is almost like a group box. Unlike the group box, the panel does not have a title on the top. But it has the support to provide the scroll bars. These scroll bars allow us to place plenty of controls in it and make us to scroll when the form is not enough to fit all the controls.

2. About the Panel Container Example

First have a glimpse at the picture staying at the end of this section. The form has a Panel Container in the top and it displays a label in it. We will place this initial label during form design. Below the panel there are two button controls. One will add the label to the panel at run-time and the other one will remove it.

The ‘Allow Auto Size for Panel’ check box, when checked, allows the Panel Container to adjust its size based on the controls in it. Just think about how the Auto Size property of the label works. C# Panel also works the same way by arranging the controls living in it. In our example, the radio buttons ‘Grow Only’ and ‘Grow and Shrink’ manages how the panel re-size itself.

The check box ‘Doc to Top’ allows the Panel Container Control to be docked on the topside of the form. This docking re-sizes the Panel when the user adjusts the size of the form.

When the ‘Auto Scroll’ check box is in the checked state and the ‘Allow Auto-Size for Panel’ is in the unchecked state, the Panel will get scroll bars when it cannot accommodate label controls. The Width and Height text boxes control the display of the scroll bar. We will learn more about these when write the code.

We will create this example to learn about the Panel Container, add controls dynamically to it and how it scrolls the controls in it. One can download the sample and have a look at the control names and properties set to it to design their own form. Below is the scree-shot of the example application.

C# Panel Container Control Example

C# Panel Container Control Example

3. Docking the C# Panel Container Control

Docking is sticking the control to any edges of the container. In our sample the ‘Dock to Top’ checkbox will dock the Panel Control to the top edge of the Form Container. If we dock a control in the top or bottom of the container, the control’s width is always equal to its container. So, when a user resizes the form, the width of the Panel Control changes along with its parent. But height remains fixed. This means, the control moves along with the Form. On the other hand, if we dock a Panel Control on the Left or Right side of the Form Container, the height will change along with the Form and width remains same.

In our example, the container of the Panel is windows form. Form treats Panel as Control. The control which we will add inside the Panel treats it as Container. Moreover, the Panel is the container for label controls which we will add dynamically through the button ‘Add Label to Panel’.

private void chkDockToTop_CheckedChanged(object sender, 
    EventArgs e)
    //Panel 01: Dock Property usage
    if (chkDockToTop.CheckState == CheckState.Checked)
        PanTopPane.Dock = DockStyle.Top;
        PanTopPane.Dock = DockStyle.None;

The code sets the ‘Dock Property’ of the Panel Control to top. This sets the Panel Control to the Top of the Windows Form which contains it. ‘Dockstyle.Top’ is an enumeration constant.

Of course, a Panel is a Container but here the Panel is a Control as well. The form treats the Panel as a Control or in other words, Panel’s container is the Form. Simply, the form acts as a container for the Panel, and the Panel acts as a container for the Label control which we will add to it in coming sections.

Dot net will see the ‘Dock Property’ of the Panel Control and then it sticks the Panel to the top of its container which is a Form here. In our case, the Panel is setting its Dock Property. C# knows where to dock the Panel Control as it knows the Container for the Panel in our example is a Windows Form.

Run and Test
  1. Run the sample.
  2. Place a check mark on the Dock to Top check box
  3. Now resize the form.

The resized form is below:

Docking a Panel in C#

Docking a Panel in C#

In the above picture, one can observe how the Panel Control resized itself on the width-wise along with the form. Also, note how the Panel changed its location in the Form because of the docking. Compare the above screenshot with the first one. You can observe there is no gap between top edge of the form and panel.

4. AutoSize & AutoSizeMode Properties

The ‘AutoSize Property’ of the Panel will take a true or false value. When AutoSize is set to true, adding or removing the controls in the Panel Container will automatically resize it. When this property is set to false and there is no scroll bar enabled to the Panel Container, the user cannot see the controls added beyond the visible portion of the Panel.

The ‘AutoSizeMode Property’ of the Panel Container deals with how the Panel will be resized. Note, with AutoSize set to true, the Panel will resize itself when we add or remove controls in it. The ‘GrowOnly Mode’ of the AutoSizeMode Property allows the Panel to grow when it does not find enough space for the new control. Moreover, the Panel Container Control will not shrink back from the last grown size when a control is taken out from it. On the contrary, the ‘GrowAndShrink Mode’ of AutoSizeMode will allow the resizing of panel control when the run-time adds or removes controls on it. Below is the code to study AutoSize Property:

private void chkAutoSize_CheckedChanged(object sender, 
    EventArgs e)
    //Panel 02: Allow Auto Size to Panel. Then 
    //set the mode in which auto size works
    if (chkAutoSize.CheckState == CheckState.Checked)
        PanTopPane.AutoSize = true;
        PanTopPane.AutoSize = false;
//Panel 03: Set the auto size mode
private void radGrowOnly_CheckedChanged(object sender, 
    EventArgs e)
    if (radGrowOnly.Checked == true)
        PanTopPane.AutoSizeMode = AutoSizeMode.GrowOnly;
private void radGrowShrink_CheckedChanged(object sender, 
    EventArgs e)
    if (radGrowShrink.Checked == true)
        PanTopPane.AutoSizeMode = 

We cannot test these properties at this time as we still need to implement dynamically adding controls to the Panel Container. Now, we do that in the coming section.

5. Dynamically Adding Controls to C# Panel Container

The Panel and all the container classes maintains a list of controls lives in it through a property. The property name is ‘Controls’ and application developers call it as ‘Controls Collection’. To add or remove the label controls to our Panel Container at run-time, we need to create the label first. Then, we add it to our Panel through its Controls Collection.

5.1 Variables for label’s location

First, we add two variables called location_x and location_y. In our example, they serve as label’s location in the Panel. Soon, we will see the usage of these two labels.

//Panel 05: Remember the Location for the Labels
int location_x;
int location_y;

5.2 Panel Constructor

In the constructor, we initialize the location variables. The existing Label control in the Panel provides value for it.

public Panel()
    //Panel 06: Save the Location
    location_x = LblReference.Location.X;
    location_y = LblReference.Location.Y;

5.3 Add Labels to Panel

Next, we handle the click event for the button ‘Add Label to Panel’. In this handler, first we create the Label Control on the fly. Our goal is to add this Control to the Panel. Panel Container requires location and size for this new Label Control to accommodate it. The existing Label Control which we created during the form design provides reference location for the new dynamic control. Using this, we calculate location for the new Label. Note, we take the size of our reference label and set it to the new Label. All the dynamically created Label in our example have same size. Finally, we give this Control to our Panel Container using add() method of the Controls Collection.

private void btnAddLabel_Click(object sender, 
    EventArgs e)
    //Panel 07: Create the label and set its properties 
    //at runtime
    Label lbl = new Label();
    location_y = location_y + LblReference.Height + 11;
    lbl.Location = new Point(location_x, location_y);
    lbl.Size = new Size(LblReference.Width, 
    //Added to avoid the offset when scroll bar is on. 
    //It is a bad trick. You should actually do 
    //coordinate conversion.
    if (PanTopPane.AutoScroll == true)
        PanTopPane.AutoScroll = false;
        lbl.Text = "Label " + location_y.ToString();
        PanTopPane.AutoScroll = true;
        lbl.Text = "Label " + location_y.ToString();
    //Panel 08: Add the control to the panel at runtime.
    //This is to experiment how the AutoSizeMode Propety 
    //in panel Works
Run & Test

Follow the steps below to check the newly added code for the Example.

  • Run the sample by pressing the F5 keyboard button.
  • After the form is visible, make sure the ‘Allow Autosize for Panel’ checkbox is not in the checked state.
  • Click the ‘Add Label to Panel’ button six times.

Only 5 labels are visible in the Panel Container Control. Where are the other two? Here comes the usage of the AutoSize Property.

  • Check the ‘Allow AutoSize for Panel’ Checkbox.

Now we will see the remaining two controls. So, the AutoSize Property changes the size of the Panel Container based on its content.

  • Now click the Remove Label from Panel button six times.

For the first two control removal, the panel got reduced in size. Then for other four controls removal, the panel just maintains its size. It is because of the ‘AutosizeMode Property’ of the Panel control. The Grow Only Mode will not shrink the control from its original size which we set during the form design.

  • Now check the radio button ‘Grow and Shrink’.
  • Add six labels as we did previously.
  • Remove the labels by clicking the corresponding button six times.

Now the Panel Container Control is reducing the size from its original size.

Adding Controls Run-time to C# Panel and the effect of AutoSize and AutoSizeMode Properties

Adding Controls Run-time to C# Panel and the effect of AutoSize and AutoSizeMode Properties

6. AutoScroll and AutoScrollMargin of Panel Container

The ‘AutoScroll Property’ of the Panel Container adds scroll bars to the Panel when it is needed and it is decided by the ‘AutoscrollMargin Property’. The AutoscrollMargin Property tells the minimal size allowed between the edge of the Panel and the border of the control it contains. When the user lowers the Panel size beyond this limit because, C# will show the scrollbar.

The event handler for the ‘Auto Scroll’ check box is below:

//Panel 04: Set the autoscroll for the Panel.
private void chkAutoScroll_CheckedChanged(object sender, 
    EventArgs e)
    if (chkAutoScroll.Checked == true)
        PanTopPane.AutoScroll = true;
        PanTopPane.AutoScroll = false;
    //Oh!! I am lazy. You better type the numbers in 
    //the width and Height boxes.
    int width = int.Parse(txtWidth.Text);
    int height = int.Parse(txtHeight.Text);
    Size dimention = new Size(width, height);
    PanTopPane.AutoScrollMargin = dimention;

Note that the AutoScrollMargin Property accepts a Size structure. The structure defines scroll margin and instructs the Panel Container when it should display the scroll bars. Have a look at the below picture:

C# Panel AutoScrollMargin Property

C# Panel AutoScrollMargin Property

To map it to our example, the black boxes are the controls and the grey box is the Panel. A and B shown are scroll margins defined by AutoScrollMargin Property. When the container resizes, and the operation hides the margin area, it will show the scroll bar. Note. this happens when we set the AutoScroll Property to true. Note, most of the developers use Panels with SplitContainer Controls.

Run & Test
  1. Run the Sample.
  2. Place a check mark on ‘Dockto Top’ check box.
  3. Enter 300 in the width text box. Place a check mark on the Auto Scroll checkbox. This will show a horizontal scroll bar because of the margin width of 300.
  4. Scroll to the right of the Panel Container Control. The distance between the sample label edge and Panel Container edge is 300. This is what we set in the ScrollMargin property. Have a look at the above drawing once again.
  5. Scroll back again to the original position.
  6. Add the label control by clicking the button multiple times. Notice that when the added labels exceeds the edge of the Panel Control a vertical scroll bar is added. Now scroll down to see the all controls.

Source Code: Download the Example from Google Drive

Categories: C#

Tags: , , , , ,

Do you like this Example? Share your thoughts!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.