views:

45

answers:

2

Let me explain. I have a List into which I am adding various ASP.NET controls. I then wish to loop through the list and set a CssClass, however not every Control supports the property CssClass.

What I would like to do is test if the underlying instance type supports the CssClass property and set it, but I'm not sure how to do the conversion prior to setting the property since I don't know the type of each Control object.

I know that I can use typeof or x.GetType(), but I'm not sure how to use these to convert the controls back to the instance type in order to test for and then set the property.


Actually I seem to have solved this, so I thought that I would post the code here for others.

foreach (Control c in controlList) {
    PropertyInfo pi = c.GetType().GetProperty("CssClass");
    if (pi != null) pi.SetValue(c, "desired_css_class", null);
}

I hope that this helps someone else as I has taken me hours to research these 2 lines of code.

Cheers

Steve

A: 

Just to follow Preet's advice I have also posted this as an answer.

foreach (Control c in controlList) {
    PropertyInfo pi = c.GetType().GetProperty("CssClass");
    if (pi != null) pi.SetValue(c, "desired_css_class", null);
}

I hope that this helps someone in the future (probably me when I google it again).

Cheers

Steve

WilberBeast
A: 

You may want to think about re-designing these classes making them implement an interface ICssControl or something along the lines which provides the CssClass property.

interface ICssControl

{ string CssClass { get; set;} }

You can then implement your logic as:

string desiredCssClass = "desired_css_class";
foreach (var control in controlList)
{
    var cssObj = control as ICssControl;
    if (cssObj != null)
        cssObj.CssClass = desiredCssClass;
}

This gets you away from needing to use reflection at all and should make for easier refactoring later on.

Edit

On re-reading you question, maybe you already have this interface and are asking how to cast it back to that interface?

Courtney de Lautour