开发者

Change document outline dynamically

开发者 https://www.devze.com 2022-12-27 14:39 出处:网络
I have a code void SomeButton_Click(object sender, EventArgs e) { if (this.Controls.Contains(Panel2)) { this.Controls.Remove(Panel2);

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 ?


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.


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);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号