Como: Executar várias ações em um objeto (Visual Basic)

In Visual Basic you must usually specify an object in every statement that calls one of its methods or accesses one of its properties. However, if you have a series of statements that all operate on the same object, you can use a With...End With structure to specify the object once for all of the statements. This can make your procedures run faster and help you avoid repetitive typing.

Exemplo

The following example sets the foreground color and font style of a Label depending on the value of a procedure argument.

Imports draw = System.Drawing
' The preceding statement must appear at the beginning of the source file.
Dim alertLabel As New System.Windows.Forms.Label
Sub alertUser(ByVal value As Long)
    With alertLabel
        If value = 0 Then
            .ForeColor = draw.Color.Red
            .Font = New draw.Font(.Font, draw.FontStyle.Bold Or draw.FontStyle.Italic)
        Else
            .Forecolor = draw.Color.Black
            .Font = New draw.Font(.Font, draw.FontStyle.Regular)
        End If
    End With
End Sub

Note the use of the Operador Or (Visual Basic) to combine font styles. This specifies the desired combination of bit flags. The Operador And (Visual Basic) would have produced 0 because all the FontStyle enumeration members use different bits.

Note also the use of the Declaração Imports (Tipo e Namespace .NET) to establish the import alias draw, which makes each reference to System.Drawing members shorter and easier to read.

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

Sub setupForm()
    Dim anotherForm As New System.Windows.Forms.Form
    Dim button1 As New System.Windows.Forms.Button
    With anotherForm
        .Show()
        .Top = 250
        .Left = 250
        .ForeColor = System.Drawing.Color.LightBlue
        .BackColor = System.Drawing.Color.DarkBlue
        .Controls.Add(button1)
        With .Controls.Item(1)
            .BackColor = System.Drawing.Color.Thistle
            .Text = "Text on button1"
        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.

Consulte também

Tarefas

Como: Transferir controle para fora de uma estrutura de controle (Visual Basic)

Como: Descartar um recurso do sistema (Visual Basic)

Como: aumentar a velocidade de acesso a um objeto com um longo caminho de qualificação (Visual Basic)

Referência

Declaração With...End With (Visual Basic)

Conceitos

Estruturas de decisão (Visual Basic)

Estruturas de loop (Visual Basic)

Outras estruturas de controle (Visual Basic)

Estruturas de controle aninhado (Visual Basic)

Outros recursos

Fluxo de controle no Visual Basic