I have a need to swap controls in a TableLayoutPanel. They are in separate rows. I've tried the suggested code but to no avail. Is there a solution this other than removing all the controls and re adding? The answer can be in C# or VB.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim c1 As Control = Me.tlp.GetControlFromPosition(0, 0)
Dim c2 As Control = Me.tlp.GetControlFromPosition(0, 1)
If c1 IsNot Nothing And c2 IsNot Nothing Then
Me.tlp.SetRow(c2, 0)
Me.tlp.SetRow(c1, 1)
End If
End Sub
Here is the code to swap controls in a TableLayoutPanel
- you have two options.
1) Swap by reference to controls:
Private Sub SwapControls(tlp As TableLayoutPanel, ctl1 As Control, ctl2 As Control)
Dim ctl1pos As TableLayoutPanelCellPosition = tlp.GetPositionFromControl(ctl1)
tlp.SetCellPosition(ctl1, tlp.GetPositionFromControl(ctl2))
tlp.SetCellPosition(ctl2, ctl1pos)
End Sub
It does not depend on where controls are located in TableLayoutPanel
- could be different rows, columns or both.
Sample usage:
SwapControls(TableLayoutPanel1, Button1, Button2)
2) Swap by column/row index:
Private Sub SwapControls(tlp As TableLayoutPanel, pos1 As TableLayoutPanelCellPosition, pos2 As TableLayoutPanelCellPosition)
Dim ctl1 As Control = tlp.GetControlFromPosition(pos1.Column, pos1.Row)
Dim ctl2 As Control = tlp.GetControlFromPosition(pos2.Column, pos2.Row)
SwapControls(tlp, ctl1, ctl2)
End Sub
Sample usage:
SwapControls(TableLayoutPanel1, New TableLayoutPanelCellPosition(0, 0), New TableLayoutPanelCellPosition(1, 0))
Solutions are based around TableLayoutPanel.SetRow help article on MSDN and some research on its decompiled representation. Both were tested and deemed working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With