Determining Object Type

From HashVB
Jump to: navigation, search

There may be times when you need to determine an object variable's type. Generic object variables can hold objects from any class. You may have a TextBox, a TabControl, and a CommandButton all in one class. But how do you determine which object you have? You have two choices to figure out an object's type.

  • TypeName
  • TypeOf...Is

TypeName

The first mean of determining an object's type is TypeName. The TypeName function returns a string and is the best choice when you need to store or display the class name of an object.

TypeName Example:

Private Sub ShowTypeName(ByVal Ctrl as Object)
   Msgbox(TypeName(Ctrl))
End Sub

TypeOf...Is

The second, and by far the best, mean of determining an object's type is TypeOf...Is. The TypeOf...Is operator is much faster than an equivalent string comparison using TypeName. The TypeOf...Is operator returns True if an object is of a specific type, or is derived from a specific type.

TypeOf...Is Example:

Private Sub CheckType(ByVal Ctrl as Object)
   If TypeOf Ctrl Is TextBox Then
      Msgbox("The control is a TextBox.")
   End If
End Sub

Practical Example

Here is a practical example of how you can use TypeOf...Is. Using Crystal Reports' Viewer control, I wanted to get rid of the Tab at the top when the report loaded. Here is what I did.

Crystal Reports Tab Removal Using TypeOf...Is (.NET Code but can be used in VB6)

Private Sub RemoveTab(crView as CrystalReportViewer)
   'Loop through each Control in the CrystalReportViewer until I find the PageView Control
   Dim Ctrl as Control, subCtrl as Control
   For Each Ctrl In crView.Controls
       If TypeOf Ctrl Is PageView Then
          
          'Loop through each Control in the PageView until I find the TabControl Control
          For Each subCtrl In Ctrl.Controls
              If TypeOf subCtrl Is TabControl Then
                 Dim tbCtrl as TabControl
                 tbCtrl = subCtrl
                 'Set Appearance to Flat and Change Size to (0,1) to Hide Tab
                 tbCtrl.Appearance = TabAppearance.FlatButtons
                 tbCtrl.ItemSize = New Size(0,1)
                 tbCtrl.SizeMode = TabSizeMode.Fixed
              End If
          Next

       End If
   Next
End Sub