共用方式為


How to: Perform Multiple Actions on an Object 

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.

Example

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 Or Operator (Visual Basic) to combine font styles. This specifies the desired combination of bit flags. The And Operator (Visual Basic) would have produced 0 because all the FontStyle enumeration members use different bits.

Note also the use of the Imports Statement 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.

See Also

Tasks

How to: Transfer Control Out of a Control Structure
How to: Dispose of a System Resource
How to: Speed Up Access to an Object with a Long Qualification Path

Reference

With...End With Statement (Visual Basic)

Concepts

Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures

Other Resources

Control Flow in Visual Basic