April 17, 2011

C# - Container Controls - Panel

1. Introduction to Panel Container

The "Container Control, Panel" is all about this article. We will see how do you use the panel control to group the controls and then we will explore the important properties of this container along with this example.

Panel container is almost like a group box and I am not going to discuss the stuff, which is already explained in the previous post for the groupbox. Unlike the groupbox, the panel does not have a title on the top. But it has the support to provide the scroll bars. These scrollbars allow you place plenty of control in it and make you scroll when the form is not enough to fit all the controls.

In this article example, we will see how the scroll bar behaves for some other property on the panel. OK let us start.

2. About the Sample

The form has a panel in the top and it displays a sample label placed on the design time. Below the panel there are two buttons one will add the label at runtime and the other one will remove the label.

The Allow auto size for panel check box, when checked, allows the panel to adjust its size based on the controls in it at the moment. Just think about how the auto size property of the label works. Panel also works the same way the content of the panel is controls, that’s all. The radio button Grow only and Grow and shrink controls how the automatic size of the panel behave.

The check box DoctoTop allows the panel to be docked on the topside of the form. This allows the panel to be resized when the form resizes.

Once the auto scroll check box is checked when the auto size is in the unchecked state the panel will get scroll bars. The Width and Height text boxes control the display of scroll bar.

This sample does not do any great thing and it is just created to explain the panel container and scrolling of the controls in it. OK. Let us move. Before that, download the sample and have look at the control names and properties set to it.

3. Docking the Panel

Docking is sticking the control to the any possible edges of the container. In our sample the Dockto Top checkbox will dock the panel to the top edge of the container. If a control is docked in the top or bottom of the container, the control width is always equal to its container. When container is resized the width of the docked control changed there by resizing it and the height will be constant. Similarly, if the control is docked in the Left or Right side of the container, the height will change along with the container and control width remains constant.

The code for the Check box UI is below:

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

The code sets the Dock property of the panel Control to top. Dockstyle.top is the enumeration constant. 

Why do I say the panel as control here? Well, the containers can behave as control also. Here, the Panel is a container for the sample label "label control". But the form treats the panel as a control or Panel’s container is the form. Simply, Form acts as container for the panel, and the panel acts as container for the  Label control. 

Dot net will see the "Dock Property" and knows where it should move and resize the control by looking at the container of the control. In our case, the panel is making a call to Dock() and Dot knows where to dock the panel as it knows the Container for the panel is the Form.

Run and Test > 01

1) Run the sample
2) Place a check mark on the Dockto Top
3) Now resize the form

Observe that the panel will resize along with the form only on the widthwise. Also, note that the panel is relocated from the design time position to the top of the form. Do not worry about the scroll bars now.

4. Panel autosize

The "AutoSize Property" of the panel will accept a Boolean true or false. When autosize is set to true, adding or removing the controls in the panel will automatically resize the panel. When this property is set to false and there is no scroll bar enabled to the container, the labels added beyond the visible portion will not be shown.

"AutoSizeMode Property" of the panel controls how the panel will be resized when the control is added to it or removed from it. The "GrowOnly Mode" of AutoSize property allows the panel to grow when the added control is in the invisible portion of the panel. And, the Panel Container will not shrink from the last set minimum size when a control is removed. The "GrowAndShrink mode" will allow the control freely resized based on addition or removal of the controls.

Below is the code for it:

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 = AutoSizeMode.GrowAndShrink;

I hope no explanation is required on the code. You can understand it easily.

5. Adding and removing control at runtime

The panel and all the container classes maintain a collection of controls as property. The property name is "Controls". Here to add or remove the label controls we need to create control first and then add it to the panel through methods offered by the Controls property. Let us look at the code.

1) First, a variable is declared to know the position of the control when we add or remove. Here location_x will not change and when I am writing I am releasing it and I do not want to make a change now. The location_y will change when we add the label and remove it.

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

2) In the constructor, we are setting the above variables from the control that is already available in the form for reference.

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

3) Next, the handler for the Add Label button will first create the label, sets the location using the variables talked in the previous two points, sets the size and text for it. Once the label is ready, it is added to the panel’s control collection. Rest the panel will do. Our job is to create the control and add it to the 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, LblReference.Height);
    lbl.Text = "Label " + location_y.ToString();

    //Panel 08: Add the control to the panel at runtime. This is to show you how the AutoSizeMode
    //          Propety for the panel Works

4) Below is the code for the removal of the label. Hope explanation is not required as it does the reverse of the previous one.

//Panel 09: Remove the label from the Panel
private void btnRemoveLabel_Click(object sender, EventArgs e)
    if (PanTopPane.Controls.Count == 0) return;
    Control.ControlCollection Controls_in_Panel = PanTopPane.Controls;
    Controls_in_Panel.RemoveAt(PanTopPane.Controls.Count - 1);
    location_y = location_y - LblReference.Height - 11;

Run and Test > 02

1) Run the sample by pressing the F5
2) When the form is visible, make sure the Allow Autosize for Panel checkbox is not checked.
3) Click the add Label to Panel button six times.
Only 4 labels were added and where is the next two? Here comes the usage of the autosize property.

4) Now check the add Label to Panel Checkbox.
Now you will see the remaining two controls. So the autosize property actually changes the size of the panel based on the content it has.

5) Now click the Remove Label from Panel button six times.
For the first two control removed, 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 will not shrink the control from its original size. The original size is the one, which was before the change happened to it by the autosize property with the mode growonly.

6) Now check the radio button Grow and Shrink
7) Add six labels as you did previously by clicking the button
8) Remove the labels by clicking the corresponding button six times.
Now the Panel is reducing the size from its original size.

6. AutoScroll and AutoScrollMargin of Panel

The "AutoScroll Property" of the panel provides the scrollbars to the Panel when it is required. OK, "when it is required" is decided by the other property AutoscrollMargin. The scroll margin actually tells the minimum size allowed between the border of the control and edge of the panel. When the size further reduced by resizing the panel, a scroll bar will be added to it.

Below is the code for it.

//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 accepts a size structure. And the structure defines scroll margin and instructs the panel when it should display the scroll bars. Look at the below picture:

To map it to our example, the black boxes are the controls and the gray box is the panel. A and B shown are scroll margins defined by AutoScrollMargin property. When the container resize operation hides the margin area, a scroll bar will be introduced when AutoScroll property is set to true.

Run and Test > 03 [Make sure autosize is unchecked]

1) Run the Sample
2) Place a check mark on dockto Top
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. The distance between the sample label edge and panel 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 label added exceeds the edge of the panel a vertical scroll bar is added. Now scroll down to see the all controls.

Source Code : Download

No comments:

Post a Comment

Leave your comment(s) here.

Like this site? Tell it to your Friend :)