Reputation: 29725
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?
Upvotes: 0
Views: 2252
Reputation: 10931
Note that if there wasn't a super class, like Control
in this case, what you're looking for would be almost identical to the Option Strict Off
version of TargetControl.Text
in that the class is not determined until runtime.
Upvotes: 0
Reputation: 5107
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.)
Upvotes: 1
Reputation: 415810
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
.
Upvotes: 2