C #: Nice way to find next and previous sibling control
What's a good way to find the next and previous siblings of a control?
So, for example, if you have a panel with several buttons, text fields, etc. Somewhere among those who have a custom control that consists of a text box and a button. When a button is clicked, for example, you want to find the name of the control that appears after that custom control.
My goal is to create a custom control that can change its position to whatever comes before or after it (if there are any, of course).
I know this must be a little trivial, but I just can't wrap my head around this ... = /
source to share
This solution is quite case specific FlowLayoutPanel
. Since it displays the controls in the order they appear in the collection of controls, the trick, of course, is to find the indices of the controls to be swapped and toggle them:
private enum Direction
{
Next,
Previous
}
private void SwapLocations(Control current, Direction direction)
{
if (current == null)
{
throw new ArgumentNullException("current");
}
// get the parent
Control parent = current.Parent;
// forward or backward?
bool forward = direction == Direction.Next;
// get the next control in the given direction
Control next = parent.GetNextControl(current, forward);
if (next == null)
{
// we get here, at the "end" in the given direction; we want to
// go to the other "end"
next = current;
while (parent.GetNextControl(next, !forward) != null)
{
next = parent.GetNextControl(next, !forward);
}
}
// get the indices for the current and next controls
int nextIndex = parent.Controls.IndexOf(next);
int currentIndex = parent.Controls.IndexOf(current);
// swap the indices
parent.Controls.SetChildIndex(current, nextIndex);
parent.Controls.SetChildIndex(next, currentIndex);
}
Usage example:
private void Button_Click(object sender, EventArgs e)
{
SwapLocations(sender as Control, Direction.Next);
}
source to share
this.Controls.SetChildIndex(panelContainerOfHeaderAndUserControl1, 0);
this.Controls.SetChildIndex(panelContainerOfHeaderAndUserControl, 1);
This worked for me. I have two panels created at runtime, but one with a fill style and the other with a vertex. The panel with the fill style overlaps the top.
Setting the order of sibling controls for controls fixes this.
source to share