1. Computing & Technology

Discuss in my forum

C# Programming Tutorial - Programming Advanced Winforms in C#

By , About.com Guide

8 of 10

Using TableLayoutPanels
Using a TableLayoutPanel

A TableLayoutpanel is an interesting container. It's a table structure organized like a 2D grid of cells where each cell contains just one control. You can't have more than one control in a cell. You can specify how the table grows when more controls are added or even if it doesn't grow, It seems modeled on an HTML table because cells can span columns or rows. Even the anchoring behavior of child controls in the container depends up on Margin and Padding settings. We'll see more about anchors on the next page.

In example Ex6.cs, I've started with a basic Two Column Table and specified via the Control and Row Styles dialog box (select the control and click the little right pointing triangle located near the top right to see a list of tasks and click the last one) that the left column is 40% and the right column 60% of the width. It lets you specify column widths in absolute pixel terms, in percentage or you can just let it AutoSize. A quicker way to get to this dialog is just click the Collection next to Columns in the Properties Window.

I've added an AddRow button and left the GrowStyle property with its default AddRows value. When the table gets full it adds another row. Alternatively you can set its values to AddColumns and FixedSize so it can't grow anymore. In Ex6, when you click the Add Controls button, it calls the AddLabel() method three times and AddCheckBox() once. Each method creates an instance of the control and then calls tblPanel.Controls.Add() After the 2nd control is added the third controls causes the table to grow. The picture shows it after teh Add Control button has been clicked once.

In case you're wondering where the default values come from in the AddCheckbox() and AddLabel() methods that I call, the control was originally manually added to the table in the designer and then the code to create it and initialize it was copied from within this region. You'll find the initialization code in the InitializeComponent method call once you click the + to the left of the Region below:

Windows Form Designer generated code

Then I copied and pasted the component creation code plus the code that initialized it. After that the control was manually deleted from the table. This is a handy technique when you want to create controls dynamically. You can leave the code for assigning the name property in, as having multiple dynamically created controls in the table doesn't appear to cause problems.

On the next page: Some Common Properties you should know

©2012 About.com. All rights reserved.

A part of The New York Times Company.