Svish Svish - 1 year ago 109
C# Question

C#: How to swap the position of two winform controls

Let's say you have two

s, Alice and Bob, and you want to swap their position. By that I mean that after the swap:

  • If they are living in the same
    , Alice should have the index of Bob and vice versa.

  • If in different
    s, Alice should have the same index as Bob, but be in Bobs
    and vice versa.

How would you do this? I am a bit unsure how to best solve this because of how the
methods work. For example using the
method to remove a control will change the index of all the controls coming after it in the collection. The SetChildIndex works in a similar way.

Edit: The parent controls of Alice and Bob are flow layout panels. This is why I want to swap their index which will in effect swap their position in the flow layout panel.

Answer Source

For the simple case, where both controls are on the same FlowLayoutPanel, use the SetChildIndex method on Controls.

Something like this ...

var alphaIndex = panel.Controls.IndexOf(controlAlpha);
var betaIndex = panel.Controls.IndexOf(controlBeta);
panel.Controls.SetChildIndex(controlAlpha, betaIndex);
panel.Controls.SetChildIndex(controlBeta, alphaIndex);

Note: I haven't handled sequence here properly - you need to put the earlier control into place first, else when the second is moved ahead of it, the resulting index will be one too high. But that's an exercise for the reader.

For the more complex case, where the controls are on different FlowLayoutPanels, the code is simpler (sequence doesn't matter so much) and more complicated (each control needs to be removed from one panel and added to the other).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download