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

Say you have two Controls, Alice and Bob, and you want to change your position. By this, I mean that after the exchange:

  • If they live in the same ControlCollection, Alice must have a Bob index and vice versa.
  • If in different ControlCollections, Alice must have the same index as Bob, but be in Bob ControlCollectionand vice versa.

How do you do this? I'm a little unsure of how to best solve this problem due to how the methods work ControlCollection. For example, using the method Removeto remove a control, the index of all the controls following it in the collection will be changed. SetChildIndex works the same way.

Edit: Alice and Bob's parent controls are stream layout panels. That's why I want to swap my index, which will actually replace their position in the stream layout panel.

+5
source share
5 answers

For the simple case when both controls are on the same FlowLayoutPanel, use the SetChildIndexmethod Controls.

Something like that...

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

Note. I didn’t handle the sequence correctly here - you need to install the previous control first, otherwise, when the second is moved in front, the resulting index will be too high. But this is an exercise for the reader.

, FlowLayoutPanel s, ( ) ( ).

+6
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);

, , ...

+1

, , . : - ControlCollection.

, , Panel:

  • PanelA PanelB.
  • PanelA Alice, PanelB Bob.
  • Bob PanelA Alice PanelB.

Alice Bob ControlCollection, Panel .

0

-, . , Control.BringToFront() ControlCollection.

:

foreach(Control _control in this.Controls)
  _control.BringToFront()

ControlCollection.

0

, ControlCollection (), , , ( , SortedList?).

SortedList, SortedList ControlCollection.

The second case will be similar to the first, except that you will have 2 SortedLists, and you would exchange Alice and Bob between them.

-1
source

All Articles