How to reverse a FlowLayoutPanel?

779 Views Asked by At

I'm trying to reverse the order of Controls in a FlowLayoutPanel.

I tried converting the ControlCollection to an array and then reversed that and cleared the ControlCollection and then readded the Controls. But this doesn't seem to have the planned effect.

Here's the code I use:

private static void ReverseLayout(Control control, bool suspend = true) {
     if (suspend) control.SuspendLayout();
     Control[] newCC = new Control[control.Controls.Count];
     control.Controls.CopyTo(newCC, 0);
     Array.Reverse(newCC);
     control.Controls.Clear();
     //control.Controls.AddRange(newCC);
     for (int i = 0; i < newCC.Length; i++) {
        newCC[i].Location = new System.Drawing.Point(); // maybe? no :\
        newCC[i].TabIndex = i; // maybe? no :\
        control.Controls.Add(newCC[i]);
     }
     if (suspend) control.ResumeLayout(false);
  }
1

There are 1 best solutions below

8
On BEST ANSWER

Your code seems more complicated than it needs to be. Try putting the controls in a List<Control> and then call reverse on it, put the collection back:

int firstTabIndex = flp.Controls[0].TabIndex;
List<Control> controls = flp.Controls.Cast<Control>().ToList();
flp.Controls.Clear();
controls.Reverse();
flp.Controls.AddRange(controls.ToArray());

For the TabIndex property, you would have to reapply the value:

for (int i = 0; i < flp.Controls.Count; ++i) {
  flp.Controls[i].TabIndex = firstTabIndex + i;
}