Let's say you have two Control
s, Alice and Bob, and you want to swap their position. By that I mean that after the swap:
ControlCollection
, Alice should have the index of Bob and vice versa.ControlCollection
s, Alice should have the same index as Bob, but be in Bobs ControlCollection
and vice versa.How would you do this? I am a bit unsure how to best solve this because of how the ControlCollection
methods work. For example using the Remove
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.
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 FlowLayoutPanel
s, 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).
Control bobParent = bob.Parent;
Control aliceParent = alice.Parent;
int bobIndex = bobParent.Controls.GetChildIndex(bob);
int aliceIndex = aliceParent.Controls.GetChildIndex(alice);
bobParent.Controls.Add(alice);
aliceParent.Controls.Add(bob);
bobParent.Controls.SetChildIndex(alice, bobIndex);
aliceParent.Controls.SetChildIndex(bob, aliceIndex);
Probably not the shortest way, but it should work...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With