[ACCEPTED]-Using Reflection to call a method of a property-reflection

Accepted answer
Score: 15

That was quick... I changed the Invoke line 1 to...

m.Invoke(p.GetValue(newControl, null), new object[] { newValue });

...and it worked :P

Score: 5

@acron, Thanks for providing a great question 16 and answer. I want to extend your solution 15 for a slightly different scenario for anyone 14 looking in the future.

Facing a similar problem 13 in the ASP.NET world I was trying to find 12 a common way to load either a System.Web.UI.Webcontrols.DropDownList OR a System.Web.UI.HtmlControls.HtmlSelect While 11 both of these have an "Items" property of 10 type "ListItemCollection", with a corresponding 9 "Add" method, they do not share a common 8 interface (as they SHOULD... hey Microsoft...) so that casting can be used.

The 7 additional challenge that your solution 6 didn't provide for is the overloading of 5 the Add method.

Without the overloads your 4 line: MethodInfo m = p.PropertyType.GetMethod(methodName); works just fine. But, when the Add 3 method is overloaded an additional parameter 2 is called for so that the runtime can identify 1 which overload to invoke.

MethodInfo methInfo = propInfo.PropertyType.GetMethod("Add", new Type[] { typeof(ListItem) });

Score: 1

The error that you are getting indicates 7 that the property in question is read only. There 6 is no set method defined. You will not 5 be able to set the value for the property 4 without a setter.

Post back with the name 3 of the property or more context and we may 2 be able to give you a better answer or an 1 alternative.

More Related questions