views:

29

answers:

2

I need to loop through all controls on ASP.NET webpage. In configuration file I have a list of control types and their properties which will I handle in some way. Now, I am interested in following: how can I get that needed property, when all I have are strings, ie names of types of controls and names of their respective properties.

Here is example: In config file I have strings:

controltype = "label" propertyname = "Text"  
controltype = "Image" propertyname = "ToolTip".

so I have something like this in my code:

List<Control> controls = GiveMeControls();  
foreach(Control control in controls)  
{  
    // in getPropertyNameFromConfig(control) I get typename of control   
    // and returns corresponding property name  from config type
    string propertyName = getPropertyNameFromConfig(control);    
    string propertyValue = getPropertyValueFromProperty(control, propertyValue);
    // !!! Don't      know how to write getPropertyValueFromProperty.  
}  

Does anyone have any idea how to develop getPropertyValueFromProperty()?

Thanks in advance,
DP

+1  A: 

You will have to use the Reflection API. With that you can inspect types and locate the properties by name, and then use the properties to get values from the control instances.

Peter Lillevold
+1  A: 

The following example implementation should do what you require:

    static string getPropertyValueFromProperty(object control, string propertyName)
    {
        var controlType = control.GetType();
        var property = controlType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        if (property == null)
            throw new InvalidOperationException(string.Format("Property “{0}” does not exist in type “{1}”.", propertyName, controlType.FullName));
        if (property.PropertyType != typeof(string))
            throw new InvalidOperationException(string.Format("Property “{0}” in type “{1}” does not have the type “string”.", propertyName, controlType.FullName));
        return (string) property.GetValue(control, null);
    }

If you have any questions about how this works, please feel free to ask in a comment.

Timwi
Thank you very much! I understood it all.
Deveti Putnik