我动态地为TableLayoutPanel生成控件。我在每一行都有一个删除按钮。当我点击它时,必须删除该行。
Dim removeBtn As New Button
AddHandler removeBtn.Click, AddressOf DeleteRow
tlp.Controls.Add(removeBtn, 5, rowCount)
我没有显示添加与上面类似的文本框的代码。我可以得到点击按钮的行号。使用此方法,如何从该行中删除所有控件。
Private Sub DeleteRow(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim currentRow As Integer = CType(CType(sender, Button).Parent, TableLayoutPanel).GetRow(CType(sender, Button))
'Using this currentRow, how to delete this Row
End Sub
答案 0 :(得分:20)
基本上你必须:
这是执行相同操作的VB.NET代码。
Public Sub RemoveRow(ByRef panel As TableLayoutPanel, ByRef rowIndex As Integer)
panel.RowStyles.RemoveAt(rowIndex)
Dim columnIndex As Integer
For columnIndex = 0 To panel.ColumnCount - 1
Dim Control As Control = panel.GetControlFromPosition(columnIndex, rowIndex)
panel.Controls.Remove(Control)
Next
Dim i As Integer
For i = rowIndex + 1 To panel.RowCount - 1
columnIndex = 0
For columnIndex = 0 To panel.ColumnCount - 1
Dim control As Control = panel.GetControlFromPosition(columnIndex, i)
panel.SetRow(control, i - 1)
Next
Next
panel.RowCount -= 1
End Sub
这是一个C#扩展方法,可以为您完成此任务。
public static void RemoveRow(this TableLayoutPanel panel, int rowIndex)
{
panel.RowStyles.RemoveAt(rowIndex);
for (int columnIndex = 0; columnIndex < panel.ColumnCount; columnIndex++)
{
var control = panel.GetControlFromPosition(columnIndex, rowIndex);
panel.Controls.Remove(control);
}
for (int i = rowIndex + 1; i < panel.RowCount; i++)
{
for (int columnIndex = 0; columnIndex < panel.ColumnCount; columnIndex++)
{
var control = panel.GetControlFromPosition(columnIndex, i);
panel.SetRow(control, i - 1);
}
}
panel.RowCount--;
}
答案 1 :(得分:3)
除了Johann和emaillenin的答案,你应该改变以下一行
panel.SetRow(control, i - 1);
到此
if (control != null) panel.SetRow(control, i - 1);
如果没有检查null,那么空字段和跨越的控件将在此处抛出错误。
答案 2 :(得分:-7)
为什么这么辛苦...... 使用 tableLayoutpanel1.Controls.Clear()
这将清除表格面板的内容