views:

92

answers:

2

I am creating .NET validators dynamically and passing the property I am invoking and the value to a method that invokes the property and supplies the value.

This is working for most of the properties. But when I try to invoke the Operator method or the Type method of the compare validator, I get an error saying the property cannot be found. The code I am using is below. I know it needs error handling, but I'm still in early development and want to see where it blows up. Through the debugger, I can see that the paramater supplied as Obj is indeed a CompareValidator and does have the properties that cannot be found. I thought it might only be finding the base properties, (I downcast to base validator in the caller), but it works on ControlToCompare which is not a member of BaseValidator. Any help would be appreciated.

    ''' <summary>
    ''' Invokes a property on the supplied object
    ''' </summary>
    ''' <param name="Obj">Object to invoke the property on</param>
    ''' <param name="PropertyName">Name of the property to invoke</param>
    ''' <param name="PropertyValue">Value of the property</param>
    ''' <returns></returns>
    ''' <remarks>Uses reflection to invoke the property</remarks>
    Private Function InvokeProperty(ByVal Obj As Object, ByVal PropertyName As String, ByVal PropertyValue As String) As Object
        Dim Params(0) As String
        Params(0) = PropertyValue
        Return Obj.GetType().InvokeMember(PropertyName, Reflection.BindingFlags.SetProperty, Nothing, Obj, Params)
    End Function
A: 

I think you're on the right path with suspecting the downcasting. What does Obj.GetType() return? The debugger will show that the parameter is a CompareValidator, because it is, but that information may not be available to the method if you have downcast it before passing it in.

Don
Unfortunately it's not the downcasting. I tried it with an actual compare validator and still get the same error. But I did notice that the properties it is failing on are also enumerations. Maybe the error message is just misleading? or it can't find Type as a string property? So if invoke member only can supply string paramaters, how do I pass an enumeration or its numeric equivalent?This question might have to be reposted with that as the title if google can't help me.
Frank
A: 

Thanks, I got it now. My approach was too simplistic. It was only working with string properties. I was getting the error because InvokeMember was looking for "public property Type as string" instead of "Public Property Type as ValidationDataType". I found this out using the following code:

           Dim info As System.Reflection.PropertyInfo = Obj.GetType().GetProperty("Type")
            Dim EnumType As Type = info.PropertyType
            info.SetValue(Obj, [Enum].Parse(EnumType, ValidationDataType.Date), Nothing)

So you live and you learn. I hope maybe this will help somebody else out also.

Frank
Glad to see you got it :)
Don