sepehr
sepehr

Reputation: 897

How to swap elements on TableLayoutPanel?

I'm having trouble with swapping two elements on TableLayoutPanel programmatically . Is it possible to swap controls housed on TableLayoutPanel during runing time , just like we are able to do it during Form designing time ? I have 25 buttons on form, one button per TableLayoutPanel cell.

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

Upvotes: 2

Views: 2577

Answers (1)

LarsTech
LarsTech

Reputation: 81675

Use GetCellPosition and 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);
}

Upvotes: 3

Related Questions