The
TableLayoutPanel
in .NET is a great control for organizing other controls on a Windows form. We here at ImageSource use it all of the time. Most developers just generate all of the rows and columns from designer and never mess with the control again at runtime. Unlike the ListBox
and ListView
controls,changing the Rows
and Columns
at runtime is not immediately obvious in the TableLayoutPanel
. The following set of code will demonstrate will demonstrate a way to accomplish this non-intuitive task.
First, we start with a very basic form with a TableLayoutPanel added to it:
Next, I add the following code to the form:
private void GenerateTable(int columnCount, int rowCount) { //Clear out the existing controls, we are generating a new table layout tableLayoutPanel1.Controls.Clear(); //Clear out the existing row and column styles tableLayoutPanel1.ColumnStyles.Clear(); tableLayoutPanel1.RowStyles.Clear(); //Now we will generate the table, setting up the row and column counts first tableLayoutPanel1.ColumnCount = columnCount; tableLayoutPanel1.RowCount = rowCount; for (int x = 0; x < columnCount; x++) { //First add a column tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); for (int y = 0; y < rowCount; y++) { //Next, add a row. Only do this when once, when creating the first column if (x == 0) { tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize)); } //Create the control, in this case we will add a button Button cmd = new Button(); cmd.Text = string.Format("({0}, {1})", x, y); //Finally, add the control to the correct location in the table tableLayoutPanel1.Controls.Add(cmd, x, y); } } }
This code, when run from our test application, will generate variable numbers of rows and columns withing the
TableLayoutPanel
. Each cell will then have button inside, displaying the cell coordinates within the button text.
tham khảo tại đây
Dynamically Generating A TableLayoutPanel
Rating: 4.5
Diposkan Oleh:
http://pdunoteit.blogspot.com/