Is there a way to remove all controls from a row in a TableLayoutPanel?

I generate controls for TableLayoutPanel dynamically. I have a delete button on each line. When I click this, this line should be deleted.

Dim removeBtn As New Button AddHandler removeBtn.Click, AddressOf DeleteRow tlp.Controls.Add(removeBtn, 5, rowCount) 

I did not show the code to add text fields similar to the ones above. I can get the line number of the pressed button. Using this, how to remove all controls from this line.

 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 
+8
tablelayoutpanel
source share
3 answers

Basically you should:

  • Get a list of controls from this line and remove them from TLP
  • Remove the appropriate line style from TLP
  • Set a new row index for each control in each row after the deleted one.
  • Reduce RowCount

Here is the VB.NET code to do the same.

 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 

Here is a C # extension method that will do this for you.

 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--; } 
+20
source share

In addition to the answers of Johann and Emailenin, you should change the following line

  panel.SetRow(control, i - 1); 

For this

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

Empty fields and also managed controls will throw an error here if theres no check for null.

+3
source share

Why is this a lot of difficulties ... using tableLayoutpanel1.Controls.Clear ()

This will clear the contents of the table pane.

-7
source share

All Articles