Question

In my windows application which uses menu strip and multiple panel containers, a panel is displayed depending on menu option

hiding all panels by manually passing names is very time consuming, is there any way to hide all panels or any way to get names of all panels in a form??

Était-ce utile?

La solution

foreach (Control c in this.Controls)
{
    if (c is Panel) c.Visible = false;
}

And you could even make that recursive, and pass in the ControlCollection instead of using this.Controls:

HidePanels(this.Controls);

...

private void HidePanels(ControlCollection controls)
{
    foreach (Control c in controls)
    {
        if (c is Panel)
        {
            c.Visible = false;
        }

        // hide any panels this control may have
        HidePanels(c.Controls);
    }
}

Autres conseils

So presumably you want to get all of the controls anywhere on the form, not just top level controls. For that we'll need this handy little helper function to get all child controls, at all levels, for a particular control:

public static IEnumerable<Control> GetAllControls(Control control)
{
    Stack<Control> stack = new Stack<Control>();
    stack.Push(control);

    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (Control child in next.Controls)
        {
            stack.Push(child);
        }
    }
}

(Feel free to make it an extension method if you think you'd use it enough.)

Then we can just use OfType on that result to get the controls of a particular type:

var panels = GetAllControls(this).OfType<Panel>();

Its clean to write something like this

foreach (Panel p in this.Controls.OfType<Panel>()) {
    p.Visible = false;
}

Argh! I was just writing the code too! :P

Control[] aryControls = new Control[]{ controlnamehere1, controlnamehere2 };
foreach (Control ctrl in aryControls)
{
   ctrl.Hide();
}

Or, alternatively:

Control[] aryControls = new Control[]{ controlnamehere1, controlnamehere1 };
foreach (Control ctrl in aryControls)
{
   ctrl.Visible = false;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top