如何将控件添加到集合的开头?

6
例如; panel1.Controls.Add(myControl);将控件添加到集合的末尾。
有没有一种方法可以在不替换开头的控件的情况下将其添加到集合开头? panel1.Controls.AddAt(0, myControl)会替换0位置上的控件。 更新 实际上,它似乎可以工作并且不会替换它。我可能弄错了。
2个回答

8

您可以使用ControlCollection.SetChildIndex方法。

将指定子控件在集合中的位置索引设置为指定的索引值。


调用 SetChildIndex 方法时,由 child 参数引用的 Control 将移动到 newIndex 指定的位置,并重新排序 Control.ControlCollection 中的其他 Control 引用以适应此移动。


1
这是正确的,但SetChildIndex会导致父控件重新布局,从而导致视觉上的混乱。在父控件上调用Control :: SuspendLayout无法防止这种情况发生。最好有一种方法可以在列表开头插入,而SetChildIndex要求先添加,然后移动,这两个操作都会导致布局。 - uglycoyote

0

试试这个:

List<Literal> persistControls = new List<Literal>();
protected void Page_Load(object sender, EventArgs e)
{          
     display();           
}

protected void commentButton_Click(object sender, EventArgs e)
{
    Literal myComment = new Literal();
    myComment.Text = "<p>" + commentBox.Text + "</p><br />";
    commentPanel.Controls.Add(myComment);
    persistControls.Insert(0,myComment);
    Session["persistControls"] = persistControls; 
    display();
}
void display()
{
    // if you already have some literal populated
    if (Session["persistControls"] != null)
    {
        // pull them out of the session
        persistControls = (List<Literal>)Session["persistControls"];
        foreach (Literal ltrls in persistControls)
            commentPanel.Controls.Add(ltrls); // and push them back into the page
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接