在 C# 中将控件值添加到另一个控件值之前
本文关键字:控件 另一个 添加 | 更新日期: 2023-09-27 18:33:33
我有一个"FlowLayoutPanel",想在其中添加一系列"UserControl":
在旧用户控件mainPanel.Controls.Add(fx);
之后添加的每个新用户控件,我想在添加的上一个用户控件之前添加新的用户控件,我该怎么做?我没有找到任何功能,例如mainPanel.Controls.AddAt(...)
或mainPanel.Controls.Add(index i, Control c)
或mainPanel.Controls.sort(...)
或......
可以使用 SetChildIndex 方法。类似的东西(也许你需要摆弄猥亵):
var prevIndex = mainPanel.Controls.IndexOf(previouslyAdded)
mainPanel.Controls.Add(fx);
mainPanel.Controls.SetChildIndex(fx, prevIndex);
通过它的声音,您想要更改 flowdirection 属性,以便将最新添加的控件添加到顶部
flowLayoutPanel1.FlowDirection = FlowDirection.BottomUp;
或者你可以
Label label1 = new Label();
flowLayoutPanel1.Controls.Add(label1);
label1.BringToFront();
纠正自己:myPanel.Controls.AddAt(index, myControl)
像这样的东西将按字母顺序添加一个控件。
FlowLayoutPanel flowLayoutPanel = ...; // this is the flow panel
Control control = ...; // this is the control you want to add in alpha order.
flowLayoutPanel.SuspendLayout();
flowLayoutPanel.Controls.Add(control);
// sort it alphabetically
for (int i = 0; i < flowLayoutPanel.Controls.Count; i++)
{
var otherControl = flowLayoutPanel.Controls[i];
if (otherControl != null && string.Compare(otherControl.Name, control.Name) > 0)
{
flowLayoutPanel.Controls.SetChildIndex(control, i);
break;
}
}
flowLayoutPanel.ResumeLayout();