Change row/column span programmatically (tablelayoutpanel)

落爺英雄遲暮 提交于 2020-01-11 04:23:07

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2763252/change-row-column-span-programmatically-tablelayoutpanel

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