问题
ContolPanel is type: FlowLayoutPanel sender is a panel that i have a click on.
How do i reorder the order my Usercontrols is set in my FlowLayoutPanel?
This is how i add my Objekts(UserControls) to my FlowLayoutPanel
private void button1_Click_1(object sender, EventArgs e)
{
int count = 0;
var panel = sender as Panel;
switch (panel.Name)
{
case "TypePanel":
ContolPanel.Controls.Add(new Type().Initialize(_ConnectionStr, _connection, _brugerLNr, _klinikLNr, _speciale, _ICPC, _segmenterStrings).SetModifiedCallBack(FilterModified));
break;
}
}
I add this like 4-5 times and have alot of diffrent once, this this is just one. What is the best method to reorder thies with a "+" and "-" button?
I thouth of saveing all the controls in a List<Controls>
And then reorder them with something like
ControlList[1] = ControlList[2]
and then inset all the controls from the list into the FlowLayoutPanel. But this just dosnt seem to work out for me. Is there a easy way of doing this smart?
回答1:
You can add your user controls to a panel and set Dock
property of your user controls to DockStyle.Top
, then as a good idea change z-order of user control using Parent.SetChildIndex to move it up or down.
To do so, add these two methods to your user controls:
public void MoveUp()
{
if (this.Parent == null)
return;
var index = this.Parent.Controls.GetChildIndex(this);
if (index <= this.Parent.Controls.Count)
this.Parent.Controls.SetChildIndex(this, index + 1);
}
public void MoveDown()
{
if (this.Parent == null)
return;
var index = this.Parent.Controls.GetChildIndex(this);
if (index > 0)
this.Parent.Controls.SetChildIndex(this, index - 1);
}
Also you can support move up using + and moving down using - keys, by overriding ProcessCmdKey
in your user control:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Add:
this.MoveUp();
break;
case Keys.Subtract:
this.MoveDown();
break;
default:
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
And also you can add a move up Button
and a move down Button
in your user control and handle Click
event of those buttons in your user control:
private void MoveUpButton_Click(object sender, EventArgs e)
{
this.MoveUp();
}
private void MoveDownButton_Click(object sender, EventArgs e)
{
this.MoveDown();
}
Since we created MoveUp
and MoveDown
public, You can move a user control up and down in form:
myUserControl1.MoveUp();
来源:https://stackoverflow.com/questions/32888790/reordering-controls-in-a-regular-panel