Can I set a property on an object that is only declared on the instance type, when I don't know the
- by WilberBeast
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