1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.