Yeah, removing an arbitrary row from a TableLayoutPanel is not at all intuitive. They really screwed up the design on this one.
The only way to remove rows is by setting the RowCount
property. This alone is strange enough; that property sure seems like it should be read-only and code that does this looks wrong to me every time I see it.
But beyond that, the consequence of this design is that you cannot remove rows from the middle. Resetting the RowCount
property will just cause rows to be lopped off of the bottom.
The workaround is a bit unwieldy, with multiple steps to get wrong:
- Remove the controls from the row you want to delete
- If applicable, move those controls to to another row.
- Move all of the controls in the other rows that come after the row you wish to delete up a row.
- Finally, remove the last row by decrementing the value of the
RowCount
property.
A quick Google search reveals that someone has written and shared code purporting to do this. It's in VB.NET, but that should be easily translated into your native dialect.
I'll admit that I've been known to just punt and set the RowHeight
of the row I wish to "remove" to 0. This way, autosizing does the work for you. You probably still want to remove the controls it contains, though.