Question

I'm trying to dynamically position controls on a page, I've got the hang of "wrapping" the controls to the next line when the width is smaller than the total width of the controls. The problem I'm having now, is getting the spacing correct.

I currently have the following;

 public void AddControl(Control controlToAdd, int parentWidth, int allRowsHeight)
 {
     RowControls.Add(controlToAdd);

     int seperationWidth = (parentWidth - RowControls.Sum(c => c.Width)) / (RowControls.Count + 1);
     int count = 0;
     foreach (Control c in RowControls)
     {
         int xLocation = (seperationWidth*(count+1));
         for (int i = 0; i < count; i++)
         {
             xLocation += (RowControls[i].Width);
         }
         c.Location = new Point(xLocation, allRowsHeight);
         count++;
     }
 }

This almost works, but as you can see from the screenshot, the controls are going a bit too far and I'm not quite sure why that is?
The "wrapping" check is basically a repetition of the seperationWidth line, it ensures of minimum spacing of 1, i.e if the spacing is less than 1, it "wraps" instead.

Perhaps there's a completely different and better way to do this? I do have access to DevExpress too if anyone is familiar with that.

EDIT:
Suspect my method has an issue with rounding. Not sure how I can get around it though;
In this instance, seperationWidth is 7 and the control widths are 128.
7+128+7+128+7+128+7+128+7=547. Not sure how I can get around this issue though?

Example

Was it helpful?

Solution

OK, so the issue here was that I was passing the Width property into the parentWidth parameter. What I actually needed to do was pass the ClientSize.Width property. This fixed the issue, buttons are now laid out correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top