如何在TableLayoutPanel上交换元素?

时间:2014-04-02 15:10:03

标签: c# winforms

我无法以编程方式在TableLayoutPanel上交换两个元素。是否有可能在运行期间交换TableLayoutPanel上的控件,就像我们能够在Form设计时间内完成它一样? 我在表单上有25个按钮,每个TableLayoutPanel单元格有一个按钮。

public void Bind(Cell tile1,Cell tile2)
{
    tableLayoutPanel1.SetRow(this.Controls.Find(tile1.Name,true).FirstOrDefault() as Button, tile2.Row);
    tableLayoutPanel1.SetColumn(this.Controls.Find(tile1.Name, true).FirstOrDefault() as Button, tile2.Column);

    tableLayoutPanel1.SetRow(this.Controls.Find(tile2.Name, true).FirstOrDefault() as Button, tile1.Row);
    tableLayoutPanel1.SetColumn(this.Controls.Find(tile2.Name, true).FirstOrDefault() as Button, tile1.Column);
}

1 个答案:

答案 0 :(得分:3)

使用GetCellPosition和SetCellPosition:

private void SwapCells(Cell tile1, Cell tile2) {
  Control c1 = tlp.GetControlFromPosition(tile1.Column, tile1.Row);
  Control c2 = tlp.GetControlFromPosition(tile2.Column, tile2.Row);
  TableLayoutPanelCellPosition cell1 = tlp.GetCellPosition(c1);
  tlp.SetCellPosition(c1, tlp.GetCellPosition(c2));
  tlp.SetCellPosition(c2, cell1);
}