SIGN UP MEMBER LOGIN:    
ARTICLE

Container Controls 2 : Panels

Posted by Sivaraman Dhamodaran Articles | Windows Forms C# April 11, 2011
This article shows how to use a Panel container to group controls and how to enable scrolling for the laid out controls on it. It explains the properties AutoSize, AutoSizeMode, Dock, AutoScroll and AutoScrollMargin.
Reader Level:
Download Files:
 

1. Introduction


This article is all about the Panel container control. We will see how to use the Panel control to group controls and then we will explore the important properties of this container along with the accompanying example.

 

A Panel container is almost like a group box and I am not going to discuss the stuff, which is already explained in the previous article for the GroupBox. Unlike the GroupBox, a Panel does not have a title in the top. But it has the support to provide scroll bars. The scroll bars allow you to place plenty of controls in it and allow you to scroll when the form is not enough to fit for 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 a 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 it's size based on the controls in it at the moment. Just think about how the autosize property of the label works. A Panel also works the same way except 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 behaves.

 

The check box Dockto Top allows the panel to be docked to the top of the form. This allows the panel to be resized when the form resizes.

 

Once the Auto Scroll check box is checked and the auto size is in the un-checked state the panel will get scroll bars. The Width and Height text boxes control the display of the 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 on. Before that, download the sample and have a look at the control names and properties set to it.

 

Pic001.JPG


3. Docking the Panel

 

Docking is sticking the control to 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 a container is resized the width of the docked control is changed, thereby 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;

else

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 a control also. Here, the panel is a container for the sample label and the label that we will add by the Add label to panel. But the form treats the panel as a control or Panel's container is the form. The .Net Framework will see the Dock property and know where it should move and resize the control by looking at the container of the control which is called the Dock property.

 

Run and Test > 01
  1. Run the sample

  2. Place a check mark on the Dockto Top

  3. Now resize the form


Pic002.JPG

Observe that the panel will only resize horizontally. 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 resizes 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 grow only mode allows the panel to grow when the added control is in the invisible portion of the panel. And, the control will not shrink from the last set minimum size. The Grow and Shrink 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;

else

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 a property. The property name is Controls. Therefore to add or remove the label controls we need to create a 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 contructor 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 then set the location using the variables described in the previous two points then sets the size and text for it. Once the label is ready, it is added to the panel's control collection. The panel will do the rest. 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

PanTopPane.Controls.Add(lbl);

}

 

4. Below is the code for the removal of the label. I 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 controls removed, the panel is reduced in size. Then for the other four controls, removal from the panel just maintains it's 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.

Pic003.JPG

 

6. AutoScroll and AutoScrollMargin of Panel

 

The autoscroll property of the panel provides scroll bars when required. OK, when it is required is determined by the other property AutoscrollMargin. The scroll margin actually tells the minimum size allowed between the border of the control and the edge of the panel. When the size is 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;

else

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 a scroll margin and instructs the panel when it should display the scroll bars. Look at the picture shown below:

Pic004.JPG

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 a container resize operation hides the margin area, a scroll bar will be introduced.

 

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 AutoScrollMargin 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.

Pic005.JPG

The sample is created in VS2005. If you have advanced IDE say yes to the conversion UI

Login to add your contents and source code to this article
share this article :
post comment
 

the object called PanTopPane is actually the Panel. Right? Yes sam. When naming the control forgot to add "l" at the end.

Posted by Sivaraman Dhamodaran Apr 12, 2011

Thank you for such a comprehensive article. It it interesting that the MSDN says that the AutoSize Property of a Panel is not relevant for the class. Also, for the benefit of others looking at the sample, the object called Panel is actually a Form; the object called PanTopPane is actually the Panel. Right?

Posted by Sam Hobbs Apr 12, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor