tags:

views:

25

answers:

2

I have a code

    void SomeButton_Click(object sender, EventArgs e)
    {
            if (this.Controls.Contains(Panel2))
            {
                this.Controls.Remove(Panel2);
            }
            else
            {
                this.Controls.Add(Panel2);
            }
    }

My problem is: the code changes document outline order of controls on my form. How can I restore previous document outline ? What properties, methods should I use ? Or is it impossible ?

A: 

Find the index before removing and for adding it, use Insert with that index. You need to access it via the explicit IList interface implementation.

private int panelIndex = 0;

void SomeButton_Click(object sender, EventArgs e)
{
   if (this.Controls.Contains(Panel2))
   {
      panelIndex = this.Controls.IndexOf(Panel2);
      this.Controls.Remove(Panel2);
   }
   else
   {
      IList ctrlsAsList = (IList)this.Controls;
      ctrlsAsList.Insert(panelIndex, Panel2);
   }
}
Oded
@Oded, I cannot find Insert method of this.Controls ...
alex
@alex - It is exposed via `IList`.
Oded
I get NonSupportedException:int _index = 0;void SomeButton_Click(object sender, EventArgs e){ if (this.Controls.Contains(Panel2)) { _index = this.Controls.IndexOf(Panel2); this.Controls.Remove(Panel2); } else { ((IList)this.Controls).Insert(_index, Panel2); }}
alex
@alex - From the documentation, it means the collection is read-only. http://msdn.microsoft.com/en-us/library/system.collections.ilist.insert%28v=VS.100%29.aspx
Oded
A: 

Use Controls.SetChildIndex( Control child, int newIndex ) after adding the control to position it at the location you want it to be in. This only works if you know the exact location in the list the control is suppose to be in.

As an alternative, have you thought about adding all the panels and then setting Visible=false until you need to show them. This of course only works if the panels are all predefined. If you are dynamically creating them, then this will not work.

JDMX
In some cases I dynamically create a control...Solution with Visible property is not what i ask but it's appropriate in some cases.I marked your answer as useful.
alex