Jeroen Mostert
8/24/2008 4:22:00 PM
Omikron wrote:
>> Visual Basic supports some convenient implicit conversions that reflected
>> properties don't. You need to supply a value of the exact same type as the
>> property, not merely one that's convertible to it. You can do this by
>> calling Convert.ChangeType() and supplying the property's type.
>>
>
> I tried this before as well. I had:
>
> Dim obj_FinalProperty As System.Reflection.PropertyInfo =
> obj_Control.GetType().GetProperty(PropertyName)
>
> If Not obj_FinalProperty Is Nothing AndAlso
> obj_FinalProperty.CanWrite = True Then
> Try
> Dim ValueType As Type =
> System.Type.GetType(obj_FinalProperty.PropertyType.AssemblyQualifiedName.ToString(),
> False, True)
>
What on earth is this supposed to achieve? Just stop at .PropertyType.
> If Not ValueType Is Nothing Then
> obj_FinalProperty.SetValue(obj_Control,
> System.Convert.ChangeType(Value, ValueType), Nothing)
> End If
>
ValueType cannot possibly be Nothing. The property must have a type and it
must be accessible, otherwise you wouldn't have been able to get it at all.
> Still Convert.ChangeType returns exception about invalid conversion.
Yes, I should have dug further. Convert only operates on system types. You
want TypeConverter here.
> So I understand there is no way to apply string value to Unit type by
> the reflection ?
Yes, there is. Here's a full snippet:
Dim PropertyInfo As PropertyInfo =
obj_Control.GetType().GetProperty(PropertyName)
If PropertyInfo Is Nothing Then Throw New
InvalidOperationException(String.Format("Property '{0}' does not exist.",
PropertyName))
If Not PropertyInfo.CanWrite Then Throw New
InvalidOperationException(String.Format("Property '{0}' is not writable.",
PropertyName))
PropertyInfo.SetValue(obj_Control,
TypeDescriptor.GetConverter(PropertyInfo.PropertyType).ConvertFromString(Value),
Nothing)
--
J.