With..End With Statement to Set Properties of Object in VB6

Saturday, August 22, 2009 ·

How to Set Object Properties using With..End With
In the earlier posting I have written that you can set object properties in two session, at design-time and at run-time, although some object properties can be set in both run-time and design-time, other can be set just in design-time, and onother can be set just in run time.

When you set object properties maybe you need to several properties at once, for example you want to set the properties of TextBox as following:

  • set font to Bold mode
  • set Font Size to 24
  • set the text with a value "Set Object Properties"

    So you can do with the following coding:
    Text1.Font.Bold = True
    Text1.Font.Size = 24
    Text1.Text = "Set Object Properties"

    However to make it easier to read, and easier to understand, you can use With..End With statement to set several Object Properies.
    You can use below code statement:
    With Text1
    .Font.Bold = True
    .Font.Size = 24
    .Text = "Set Object Properties"
    End With

    Example:
    Create a screen design like below image:
    How to Set Object Properties using With..End With
    Note: Set property "Multiline" of Text1 and Text2 to "True".

    Double-click command1 button.
    Write below coding:
       Text1.Text = "One by one set object properties"
    Text1.Font.Bold = True
    Text1.Font.Size = 24
    Text1.FontUnderline = True

    Double-click command2 button.
    Write below code statements:
    With Text2
    .Text = "Using With..End With to set object properties"
    .Font.Bold = True
    .Font.Size = 24
    .FontUnderline = True
    End With

    So your coding should like below listing:
    Private Sub Command1_Click()
    Text1.Text = "One by one set object properties"
    Text1.Font.Bold = True
    Text1.Font.Size = 24
    Text1.FontUnderline = True
    End Sub
    Private Sub Command2_Click()
    With Text2
    .Text = "Using With..End With to set object properties"
    .Font.Bold = True
    .Font.Size = 24
    .FontUnderline = True
    End With
    End Sub

    Now run our program, click command1 button, and then also click command2 button.
    Your program sholud like screenshot in top of this posting.


  • 0 comments:

    Post a Comment