Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRangeException with foreach

Edit: look at the bottom for a halfway reason why this is happening

I've a very strange IndexOutOfRangeException (as said in title). It happens when I use foreach to iterate over the controls of a control (recursive FindControl).

strange error 1

I then thought to add an additional check that makes sure root.Controls.Count > 0. However I keep getting the exception, while the debugger clearly says Count == 0.

strange error 2

The root in question is a FormView. If anyone has any ideas why a simple property check throws an IndexOutOfRangeException, please enlighten me!

Exception stackTrace (yes it is complete):

   at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)

Code:

public static Control FindControlRecursive(this Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }

    if (root.Controls.Count > 0)
    {
        foreach (Control c in root.Controls)
        {
            Control t = c.FindControlRecursive(id);
            if (t != null)
            {
                return t;
            }
        }
    }

    return null;
}

EDIT:

I've tried to use the native FindControl function, this throws the same identical error.


Specific question:

How can foreach throw an IndexOutOfRangeException on a native collection.


EDIT2:

Somehow this seems related to using a ObjectDataSource, I wasn't filling in the inputparameters correctly, but I wasn't getting any errors there. Perhaps this corrupted the FormView (that was using that datasource) somehow. I'm still interested to know how this can happen without errors thrown before accessing the childcontrols.

like image 958
Destrictor Avatar asked Oct 21 '22 19:10

Destrictor


1 Answers

Rather than Controls.Count, try using Control.HasControls(), might get around the issue.

like image 81
Tanner Avatar answered Oct 24 '22 12:10

Tanner