R – programmatically set the object type for a DirectCast command

castingdirectcastvb.net

I'm helping a colleague develop a "catch all" type error handler for some controls his application. What he wants to do is pass the object that has the error, and the type of that object, such a TextBox or ComboBox, and then call the DirectCast method within his handler to properly address the Text attribute within it. In general, the method is looking like this:

Protected Sub SpecialErrorHandler(ByVal TargetControl As Object, ByVal ControlType As String)

   MessageBox.Show("Bad Juice: " & DirectCast(TargetControl, ControlType(ObjType)).Text)

End Sub

So far any attempts to do a type conversion within the DirectCast method (since it is expecting an object in the general signature) or to even pass in the a Type object properly set is not working.

Any ideas here, or is this one of those "Casting doesn't work that way." type scenarios?

Best Answer

DirectCast() needs a real type at compile time, so it knows what the result of the call looks like. The best you can hope for here is to cast to a common base type for each of the objects you're expecting. In this case you're lucky have in that you have a fairly useful base type: Control.

Related Topic