Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say you have two Controls, 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 ControlCollection, Alice should have the index of Bob and vice versa.
  • If in different ControlCollections, 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.

like image 318
Svish Avatar asked Sep 01 '09 08:09

Svish


2 Answers

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).

like image 124
Bevan Avatar answered Sep 28 '22 05:09

Bevan


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...

like image 20
Thomas Levesque Avatar answered Sep 28 '22 04:09

Thomas Levesque