runat="server" div causes System.Web.HttpException when accessed from control collection

CptSupermrkt picture CptSupermrkt · Mar 28, 2012 · Viewed 7.3k times · Source

I have a div that is runat="server". The div is contained in a panel, and within the div are some controls. All of the controls outside of the div (but within the panel) are cleared when I run my "ClearControlsInPanel()" method, which looks like this:

public static void ClearControlsInPanel(Panel paneltoclear, string[] ignorelist)
{
    foreach (Control c1 in paneltoclear.Controls)
    {
        if (c1 is TextBox)
        {
            if (!ignorelist.Contains(c1.ID.ToString()))
            {
                ((TextBox)c1).Text = "";
            }
        }
        if (c1 is DropDownList)
        {
            if (!ignorelist.Contains(c1.ID.ToString()))
            {
                ((DropDownList)c1).SelectedIndex = 0;
            }
        }
        //etc.
    }
}

Once the div is reached, I cannot see the controls in it, and thus none of those controls get cleared. Ironically I found a guy who made a post about the exact same thing, Why adding runat=server to a div tag throws an exception of type 'System.Web.HttpException in controls collection? But the thread ends, with no real solution or explanation.

The full exception is:

base {System.Web.UI.HtmlControls.HtmlContainerControl} = {InnerText = 
'((System.Web.UI.HtmlControls.HtmlContainerControl)
(((System.Web.UI.HtmlControls.HtmlGenericControl)(paneltoclear.Controls._controls
[165])))).InnerText' threw an exception of type 'System.Web.HttpException'}

Please assume that this must remain a runat server div, and cannot be changed to a panel. (I'm almost certain changing it to a panel will solve it, but we have other requirements that need this to be a runat server div (long story)).

Answer

Adam picture Adam · Mar 28, 2012

A panel is rendered into a div anyway, so why the div? I see no requirement for it and it solves this issue rather quickly :)