Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change row/column span programmatically (tablelayoutpanel)

I have a tablelayoutpanel. 2x2 - 2 columns 2 rows.

For example, I added a button button1 in a 1 row, second column. button1 has a dock property set to Fill. VS Designer allows to set column/row span properties of button1.

I want an availability to change row span property of button1 programatically, so it can fill all second column(1 row and second row) and availability to set it back.

How?

like image 249
Александр Д. Avatar asked May 04 '10 06:05

Александр Д.


2 Answers

What about this code?

private void button1_Click(object sender, EventArgs e)
{
    var control = sender as Control;

    if(control == null)
        return;

    if (1 == tableLayoutPanel1.GetRowSpan(control))
    {
        tableLayoutPanel1.SetRowSpan(control, 2);
    }
    else
    {
        tableLayoutPanel1.SetRowSpan(control, 1);
    }
}
like image 67
Oliver Avatar answered Nov 12 '22 14:11

Oliver


While I find the current up-voted answer quite adequate, it also appears slightly messier than need be. You must add the controls to the tableLayoutPanel before setting their properties.

Visual Studio (2013 and likely other versions) will show these properties as part of the control. When in reality, they are part of the tableLayoutPanel.

Explanation:

tableLayoutPanel.Controls.Add(**control**, x, y)
tableLayoutPanel.SetColumnSpan(**control**, '# of cols to span')

Example:

tableLayoutPanel1.Controls.Add(**button1**, 0, 0);
tableLayoutPanel1.SetColumnSpan(**button1**, 2);
tableLayoutPanel1.SetRowSpan(**button1**, 3);

Result: A button which 'occupies' this space. (Provided it is large enough to cover the area. Even if it does not 'cover' the space, it will still 'reserve' it.)

O O X X X
O O X X X
O O X X X
X X X X X
X X X X X

Setting the span larger than the size of the grid will.. : NOT change the grid size. NOT crop/edit the number to the size of the grid. NOT throw an error at compile.

It WILL act/perform as if the span was set to the current grid (tableLayoutPanel) maximum size. This is only relevant if the TLP/grid size changes.

If you add two controls two the same grid location programmatically, the first control in a grid keeps its location. Any subsequently added control gets pushed to the next cell block. If a 'span' is added, it will treat that cell block as used and continue searching for an unused cell block.

Ex: label1, label2 and label3 are added to 0,0.

  • label1 will appear in 0,0
  • label2: 0,1
  • label3: 0,2

Ex 2: label 1 has a row span of 2.

  • label1: 0,0
  • label2: relocated to 0,2
  • label3: 0,3

After you have selected the correct grid point and spans, you can then further optimize your layout using the dock and anchor properties.

like image 21
Branden Avatar answered Nov 12 '22 13:11

Branden