1

I have a generic user control:

public partial class SearchBoxGeneric<T> : UserControl where T : class
{
    private T value;

    public virtual T Value
    { 
        get {return this.value;}
        set {set this.value = value}
    }
}

And I have a number of user controls that inherit from this base control, overriding Value property.

I loop through the form's controls and get the value based on the control type:

for (Control c in this.Controls
{
    switch (c.GetType().Name)
    { 
        case "TextBox":
            //Do something...
            break;
    }
} 

But how can I get the value of the generic user controls?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • Lots of bad design here : deriving from UserControl, that is generic, not enforcing that property by making it abstract and comparing types using a string. You should think of a better approach. – aybe Mar 25 '15 at 14:34

2 Answers2

0

Well to get all instances of SearchBoxGeneric<T> you could use:

this.Controls.Where(c => c.GetType().BaseType == typeof(SearchBoxGeneric<>).BaseType)

but then you'd have to use reflection to know what T is for each control. If there are just a few types that SearchBoxGeneric supports you could query each individually:

var stringBoxes = this.Controls.OfType<SearchBoxGeneric<string>>()
var intBoxes = this.Controls.OfType<SearchBoxGeneric<int>>()

etc.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You can use the IsSubclassOfRawGeneric method from another answer to determine whether the control inherits from SearchBoxGeneric<>.

static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != null && toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (generic == cur) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}

Then you can get the Value via reflection:

if (IsSubclassOfRawGeneric(typeof(SearchBoxGeneric<>), c.GetType()))
{
    var prop = c.GetType().GetProperty("Value");
    object value = prop.GetValue(c);
    Console.WriteLine(value);
}

Or using dynamic:

if (IsSubclassOfRawGeneric(typeof(SearchBoxGeneric<>), c.GetType()))
{
    dynamic dynObj = c;
    object value = dynObj.Value;
    Console.WriteLine(value);
}
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122