< Previous lesson | Visual Basic Tutorial | Content of this Chapter | Next lesson >

How to delete VB Object?

Deleting object means you release the reference memory from that object. You can do that by setting the object to nothing.
Syntax: Set objectName = Nothing

If you use VB controls as your object, you can delete the object by unloading it.
Syntax: Unload controlName

Project Using Object

  1. Make a new Standard Exe project
  2. To see how you create new object at run time, type the following code into the form.
    Private Sub Form_Click()
    Dim myform As Form1

    Set myform = New Form1
    End Sub
  3. Add one text box and two command button.
  4. The following code control the existing object, but do not create new object. Type the following code in to the command1 button:
    Private Sub Command1_Click()
    Dim anyText As TextBox
    Set anyText = Text1
    anyText.Text = "Hello"
    End Sub
  1. In the following code you use generic object variable Control. Using a generic control variable you can refer to any control on any form in an application. Add two more label control into the form. Then, type the following code in the command2 button:
    Private Sub Command2_Click()
    Dim i As Integer
    Dim anyControl As Control
    For i = 0 To 5
    Set anyControl = Me.Controls(i)
    If Me.Controls(i) <> Me.Text1 Then
    anyControl.Caption = "I am control No " & i
    End If
    End Sub
  2. Run the program and click the form and the first two command buttons. Can you guess what the control number of the text box is?
  3. Add one more command button and type this code:
    Private Sub Command3_Click()
    Unload Me
    End Sub
  4. Run the program and click the form and the second command buttons (Command2). Did you see any change in the control number from the previous run?
  5. To close the program, go to Visual Basic and end the program.

There are three generic object types in Visual Basic that you can use: Form , Control (Any control in your application) and Object (Any object). Generic object variables are useful when you don't know the specific type of object a variable will refer to at run time. For example, if you want to write code that can operate on any form in the application, you must use a generic form variable.

< Previous lesson | Visual Basic Tutorial | Content of this Chapter | Next lesson >