How to add a control to the beginning of a collection?

For instance:

panel1.Controls.Add(myControl); add to the end of the collection.

Is there any way to add to the beginning of the collection without replacing the first at the beginning?

panel1.Controls.AddAt(0, myControl) replaces the control with 0.

Update

it actually works, not a replacement for it. I may have been mistaken.

+4
source share
3 answers

You can use the ControlCollection.SetChildIndex method.

Sets the index of the specified child control in the collection to the specified index value.


When SetChildIndex is SetChildIndex , the Control pointed to by the child parameter moves to the position indicated by newIndex, and the other Control links in Control.ControlCollection reordered to adjust the move.

+4
source

try the following:

 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 } } 
0
source

try: panel1.Controls.insert(0, myControl)

-4
source

All Articles