views:

15

answers:

1

I am trying to populate a container with any number of controls that have the same height and width. I allow this container to be shrunk or grown by the user and the container will organize the controls so that it fits the most controls on one row as possible. Here is the code to organize it:

        int row = 0;
        int column = 0;            
        for (int i = 1; i <= controls.Count; i++)
        {
            controls.Values[i-1].Top = row * controls.Values[0].Height;
            controls.Values[i-1].Left = column * controls.Values[0].Width;

            if (i % controlsPerRow == 0)
            {
                // This finishes a row
                row++;
                column = 0;
            }
            else
            {
                column++;
            }
        }

The problem i run into is that on the first iteration of the loop, I will be multiplying the control height by the row and assigning that value to the control Top property. The first row is 0 and the first height is 165. 0 * 165 = 0, but the Top property contains a magical -20 after assigning the 0.

Anyone have any idea how this can happen?

+2  A: 

You're trying to rewrite the FlowLayoutPanel.
Consider using it instead.


Also, it looks like your controls field is a Dictionary<Something, Control>.
Be aware that the iteration order of Dictionary.Values is not guaranteed, meaning that you aren't looping over the controls in the order that they were added to the dictionary.

SLaks