8

我为 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
4

3 回答 3

20

基本上你必须:

  • 从该行获取控件列表并将它们从 TLP 中删除
  • 从 TLP 中删除相应的行样式
  • 为删除后的每一行中的每个控件设置新的行索引
  • 减少行数

这是执行相同操作的 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--;
}
于 2011-06-01T13:49:50.183 回答
3

除了 Johann 和 emaillenin 的答案之外,您还应该更改以下行

    panel.SetRow(control, i - 1);

对此

    if (control != null) panel.SetRow(control, i - 1);

如果没有检查空值,空字段和跨区控件将在此处引发错误。

于 2011-08-11T10:47:12.823 回答
-7

为什么这么辛苦...使用 tableLayoutpanel1.Controls.Clear()

这将清除表格面板的内容

于 2013-02-12T06:10:41.267 回答