Export (0) Print
Expand All

Performing Multiple Actions on an Object

Visual Studio .NET 2003

Often, you need to perform several different actions on the same object. For example, you may need to set several properties or execute several methods for the same object.

To set multiple properties for the same object

  • One way to do this is to write several statements using the same object variable, as in the following code:

    Private Sub UpdateForm()

       Button1.Text = "OK"

       Button1.Visible = True

       Button1.Top = 24

       Button1.Left = 100

       Button1.Enabled = True

       Button1.Refresh()

    End Sub

    However, you can make this code easier to write and read by using the With...End With statement, as in the following code:

    Private Sub UpdateForm2()

       With Button1

          .Text = "OK"

          .Visible = True

          .Top = 24

          .Left = 100

          .Enabled = True

          .Refresh()

       End With

    End Sub

    You can also nest With...End With statements by placing one inside another, as in the following code:

    Sub SetupForm()
       Dim AnotherForm As New Form1()
       With AnotherForm
          .Show()   ' Show the new form.
          .Top = 250
          .Left = 250
          .ForeColor = Color.LightBlue
          .BackColor = Color.DarkBlue
          With AnotherForm.Textbox1
             .BackColor = Color.Thistle   ' Change the background.
             .Text = "Some Text"   ' Place some text in the text box.
          End With
       End With
    End Sub
    

Within the nested With statement, however, the syntax refers to the nested object; properties of the object in the outer With statement are not set.

See Also

Calling a Property or Method Using a String Name

Show:
© 2015 Microsoft