2

Currently I am trying to extract a collection of dynamically created controls (checkboxes and dropdownlists) from a recursive control collection (repeater). This is the code I am using.

private void GetControlList<T>(ControlCollection controlCollection, ref List<T> resultCollection)
{
    foreach (Control control in controlCollection)
    {
        if (control.GetType() == typeof(T))
            resultCollection.Add((T)control);

        if (control.HasControls())
            GetControlList(controlCollection, ref resultCollection);
    }
}

I am having problems with the following line:

resultCollection.Add((T)control);

I get the error ...

Cannot convert type 'System.Web.UI.Control' to 'T'

Any ideas?

Andy Evans
  • 6,195
  • 17
  • 62
  • 112

2 Answers2

5

Problem:

Since T can be a reference type or a value type, compiler needs more information.

You can not convert and Integer to Control.

Solution:

To fix this, add where T : Control or where T : class (a more general) constraint to state that T will always be a reference type.

Example:

private void GetControlList<T>(ControlCollection controlCollection, ref List<T> resultCollection)
where T : Control
{
    foreach (Control control in controlCollection)
    {
        //if (control.GetType() == typeof(T))
        if (control is T) // This is cleaner
            resultCollection.Add((T)control);

        if (control.HasControls())
            GetControlList(control.Controls, ref resultCollection);
    }
}
  • You also don't need ref keyword. Since, List is a reference type, it's reference will be passed.
Community
  • 1
  • 1
decyclone
  • 28,886
  • 5
  • 58
  • 76
  • 1
    As @codethis mentioned in another comment, the last line should be GetControlList(control.Controls, ref resultCollection); – s_hewitt Dec 16 '10 at 17:04
3

Change it to

var c = control as T;
if (c != null)
    resultCollection.Add(c);

This will be faster than your cod, since it doesn't call GetType().
Note that it will also add controls that inherit T.

You'll also need to constrain the type parameter by adding where T : Control.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896