Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all controls in an ASP.NET Panel?

I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.

When I need to come to this page. I need to show the Page if these controls have any values. How to do this?

like image 255
balaweblog Avatar asked Nov 10 '08 11:11

balaweblog


3 Answers

I know this is an old post, and I really liked christian libardo's solution. However, I do not like the fact that in order to yield an entire set of elements to the outer scope I would have to iterate over those elements yet again only to yield those to myself from an inner scope to the current scope. I prefer:

IEnumerable<Control> getCtls(Control par)
{    
    List<Control> ret = new List<Control>();
    foreach (Control c in par.Controls)
    {
        ret.Add(c);
        ret.AddRange(getCtls(c));
    }
    return (IEnumerable<Control>)ret;
}

Which allows me to use it like so:

foreach (Button but in getCtls(Page).OfType<Button>())
{
    //disable the button
    but.Enabled = false;
}  
like image 126
theoski Avatar answered Oct 04 '22 07:10

theoski


It boils down to enumerating all the controls in the control hierarchy:

    IEnumerable<Control> EnumerateControlsRecursive(Control parent)
    {
        foreach (Control child in parent.Controls)
        {
            yield return child;
            foreach (Control descendant in EnumerateControlsRecursive(child))
                yield return descendant;
        }
    }

You can use it like this:

        foreach (Control c in EnumerateControlsRecursive(Page))
        {
            if(c is TextBox)
            {
                // do something useful
            }
        }
like image 21
Cristian Libardo Avatar answered Oct 04 '22 07:10

Cristian Libardo


You can loop thru the panels controls

foreach (Control c in MyPanel.Controls) 
{
   if (c is Textbox) {
        // do something with textbox
   } else if (c is Checkbox) {
        /// do something with checkbox
   }
}

If you have them nested inside, then you'll need a function that does this recursively.

like image 30
GeekyMonkey Avatar answered Oct 04 '22 06:10

GeekyMonkey