我需要在 TableLayoutPanel 中交换控件。它们在不同的行中。我已经尝试了建议的代码,但无济于事。除了删除所有控件并重新添加之外,还有其他解决方案吗?答案可以使用 C# 或 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
最佳答案
这是在 TableLayoutPanel
中交换控件的代码 - 您有两个选择。
1) 通过引用控件交换:
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
它不取决于控件在 TableLayoutPanel
中的位置 - 可以是不同的行、列或两者。
示例用法:
SwapControls(TableLayoutPanel1, Button1, Button2)
2) 按列/行索引交换:
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
示例用法:
SwapControls(TableLayoutPanel1, New TableLayoutPanelCellPosition(0, 0), New TableLayoutPanelCellPosition(1, 0))
解决方案基于 TableLayoutPanel.SetRow MSDN 上的帮助文章及其反编译表示的一些研究。两者都经过测试并被认为有效。
关于c# - 在 TableLayoutPanel Visual Studio 中交换控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324551/