Identify Controls in VB Using TypeOf

Discussion in 'Visual Basic [VB]' started by pradeep, Jan 15, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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:
    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:
    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
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice