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>开发者_如何学Python;
''' <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
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.
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.
精彩评论