C# ASP.NET GetType() with WebUserControl issue

11k views Asked by At

In the project I have some custom WebUserControls for form elements (they encapsulate some standard validators and other system specific functions). My user controls are "DropDownListField" and "TextBoxField". In the code behind of a page I have this code:

string parameterValue = null;
foreach (object control in myMultiView.Views[myMultiView.ActiveViewIndex].Controls)
{
    if (control.GetType() == typeof(DropDownListField))
        parameterValue = ((DropDownListField)control).Value;
    if (control.GetType() == typeof(TextBoxField))
        parameterValue = ((TextBoxField)control).Value;
}

For some reason the "if" statements always return false even when I step through the code and see that "control" is getting assigned my web user control. This code is in another place in the project exactly the same except in the other location the standard .net controls "TextBox" and "DropDownList" are used and in the other location the code works.

Does anybody know why this wouldn't work with web user controls?

UPDATE: Hmm so in debugging I found this:

?control.GetType();
BaseType: {Name = "DropDownListField" FullName = "WebUI.UserControls.Fields.DropDownListField"}
?typeof(DropDownListField);
BaseType: {Name = "UserControl" FullName = "System.Web.UI.UserControl"}

So typeof is just recognizing they are user controls not the full type it seems.

Does anybody know how I would check for a specific user control type?

3

There are 3 answers

2
Steven Jeuris On BEST ANSWER

I'm guessing they aren't the same type, use debugging to find out the actual type.

Also, try using the 'is' keyword instead.

1
Jason Kealey On

PS: It might be cleaner for you to say if (control is DropDownListField)

I don't recall if a view directly includes its children in Controls, but I wouldn't be surprised if Controls contained only one element, which would be a container of some sorts. Therefore, your controls are potentially in Controls[0].Controls or even further down. I would advise you create a method that finds the child recursively.

Actually, your controls should all implement a common interface (example:

interface ICustomFieldWithValue { string Value {get; set; }}

). Your resulting code would be much cleaner.

2
Khuram Shahzad On

c2.GetType().ToString() == "System.Web.UI.WebControls.Label"