我在以编程方式交换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);
}

最佳答案

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

关于c# - 如何在TableLayoutPanel上交换元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22815727/

10-12 18:49