views:

398

answers:

2

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?

+1  A: 

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.

Joel Coehoorn
I had a hunch, but wanted to get with the gurus here first. Thanks!
Dillie-O
+1  A: 

You can use reflection to extract the property. Also, if you know the object is always a Control, why not cast it to Control then get the Text property of the control?

Control errorObject = (Control)TargetControl;
MessageBox.Show("Error..."+errorObject.Test));

(sorry for the C# code, not that familiar with VB, but should be almost the same.)

Ricardo Villamil
No worries on the C# code. I'm passing word to him with the potential for that. If he doesn't need anything more complex than the Text field, he should be all set. Thanks!
Dillie-O