Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   Identify Controls in VB Using TypeOf (http://www.go4expert.com/articles/identify-controls-vb-using-typeof-t2560/)

pradeep 15Jan2007 17:59

Identify Controls in VB Using TypeOf
 
Often in your code procedures, you may need to determine what typeof control your code has accessed. For instance, you may want to alter the text on every command button on a form. Or you may want to change the properties for several different controls. In such instances, you have several ways to test for a control type. The most efficient and fastest method is the TypeOf operator.

Unlike other methods of determining a control's type, such as theTypeName property, the TypeOf keyword doesn't need several roundtrips to the Registry to obtain the information it needs. As a result, it reduces the processing drag necessary for your code.

This keyword must appear in an If...Then statement, like so:

Code: VB

If TypeOf ctl Is CommandButton Then
    'Do something
End If

The following example shows an example of how to use this keyword in a procedure.

Code: VB

Private Sub Command1_Click()
      Dim ctl As Control
      Dim str As String
      For Each ctl In Me.Controls
          If TypeOf ctl Is CommandButton Then str = "CommandButton"
          If TypeOf ctl Is TextBox Then str = "TextBox"
          If TypeOf ctl Is OptionButton Then str = "OptionButton"
          If TypeOf ctl Is DriveListBox Then str = "DriveListBox"
          If TypeOf ctl Is DataCombo Then str = "DataCombo"
          MsgBox str
      Next ctl
  End Sub



All times are GMT +5.5. The time now is 08:20.