Q: Reflection and Getproperty/Setvalue

  • Thread starter Thread starter JustMe
  • Start date Start date
J

JustMe

I likely just don't fully understand how reflection works, but what I want
to do is allow the user to manually enter in any field name (ie. BackColor,
ForeColor, Size, etc..) and a corresponding value, and then change the value
of that property at runtime.

I'm trying:
Dim pi As System.Reflection.FieldInfo

Dim x As Control = CType(MyControl, Control)

pi = x.GetType().getfield(Param2, Reflection.BindingFlags.NonPublic Or
Reflection.BindingFlags.GetField Or Reflection.BindingFlags.Instance)

pi.SetValue(Nothing, NewValue)

When I run this code I do not get an error on the pi = x.GetType line,
however pi always ends up being 'nothing'. When I try to run this in
imeediate mode I get a 'Parameter is incorrect' error.

Any suggestions?

Thanks in advance,
--Terry
 
As these are Properties and not fields you should use GetProperty() instead.
The BindingFlags should be Public and Instance for a public member property.
Note that many controls will not make use of the BackColor / ForeColor
properties although this functionality will be available in the upcoming
SP2.
Also your setvalue must specify the object to use (the control in this
case):-

Dim pi as System.Reflection.PropertyInfo
Dim x As Control = CType(MyControl, Control)

pi = x.GetType().GetProperty(Param2, Reflection.BindingFlags.Public
OrReflection.BindingFlags.Instance)

pi.SetValue(x, NewValue, null)

Peter
 
Hi Peter ...

Thank you! That put me on the right track. I had been consistently trying
to access the 'BackColor' property. As well, it appears that the fieldname
property is 'case sensitive' which wasn't helping matters any.

Thanks again Peter.
--Terry
 
Note that while these are case sensitive by default, you can pass the
BindingFlag.IgnoreCase along with your flags to do a case insensitive lookup

Peter

--
Peter Foot
Windows Embedded MVP
OpenNETCF.org Senior Advisor
www.inthehand.com | www.opennetcf.org
 
Also keep in mind that BindingFlags.GetField is only applicable to
Type.InvokeMember call. All GetXXX (Property/Field/Method/Constructor/Event
etc) use combination of Public/NonPublic/Instance/Static/Ignorecase
 
Back
Top