Change row/column span programmatically (tablelayoutpanel)

孤街浪徒 提交于 2019-12-01 02:32:10

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);
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!