Reflection - Getfield/Setvalue question ...

  • 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.

Using 'hardcoded values', I'm trying:

Dim pi As System.Reflection.FieldInfo
Dim strFieldName as string = "BackColor"
Dim NewValue as Color = Color.Red
Dim x As Control = CType(MyControl, Control)

pi = x.GetType().getfield(strFieldName, 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
 
You should use GetProperty rather than GetField as you are accessing
Properties not instance fields. The following code will work without error:-

Dim pi As System.Reflection.PropertyInfo

pi = cntrl.GetType().GetProperty("BackColor")

pi.SetValue(cntrl, Color.Red, Nothing)



Note that until SP2 controls such as the Button etc will not respond to
changes in the BackColor property as this is set with the system defaults.
If you pass your form in as the control then the back color will get
updated.



Peter
 
Back
Top