RowStyles and Rows doesn't match in TableLayoutPanel?

.net, c#, tablelayoutpanel, winforms

Solution

I've tried digging into the issue. The problem is that you did not add rows in a correct way. To add rows correctly, you have to ensure the value of `RowCount` and the number of `RowStyles` to be equal. You can see this right in the `Form1.Designer.cs` in the autogenerated code for the tableLayoutPanel. So you should do something like this:

//add a new row
tableLayoutPanel.RowCount++;
tableLayoutPanel.RowStyles.Add(newRowStyle);

The mismatching in fact does not cause a very serious problem. When the `RowStyles.Count` is larger than the actual `RowCount`, all the top RowStyles (which has count being equal to `RowCount`) will be used to style the rows, the rest can be seen as reserve. When the `RowStyles.Count` is smaller than the actual `RowCount`, there will be some rows not having any style and may be collapsed. Anyway using the code I posted above to add a new row will help you avoid any issue. The point is we have to ensure the number of rows and the number of `RowStyles` to be equal.

Problem

We are hiding controls in a `TableLayoutPanel`. We have been using the following code for a while for hiding a row that shouldn't be visible. ``` int controlRow = m_panel.GetPositionFromControl(control).Row; m_panel.RowStyles[controlRow].SizeType = SizeType.Absolute; m_panel.RowStyles[controlRow].Height = 0; ``` Now we have been adding more rows, and all of a sudden we have problems with the indexes. There are fewer RowStyles than Rows. Is there something fishy going on, or have I misunderstood how the `TableLayoutPanel` works?

Original source