How to: Pass Objects to Procedures
Updated: October 2008
Visual Basic allows you to pass objects as arguments to procedures in the same way that you pass other types of arguments. The following procedures demonstrate how.
To pass a new instance of a form to a procedure
Create a Windows Forms application. Add a button, Button1, to Form1.
Copy the following code into Form1.vb:
Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim newForm As New Form1 newForm.Show() CenterForm(newForm) End Sub Sub CenterForm(ByVal TheForm As Form) ' Centers the form on the screen when you click the button. Dim RecForm As Rectangle = Screen.GetBounds(TheForm) TheForm.Left = CInt((RecForm.Width - TheForm.Width) / 2) TheForm.Top = CInt((RecForm.Height - TheForm.Height) / 2) End Sub
You can also pass an object as an argument by reference and then, inside the procedure, set the argument to a new object.
To pass an object reference to a procedure on another form
Create a Windows Forms application. The application will contain a form named Form1.
Add a second Windows Form, Form2, to the application.
Place a picture box control on each form.
Name the picture box on Form1 PictureBox1.
Name the picture box on Form2 PictureBox2.
Assign a picture to PictureBox2 by clicking the Image property in the Properties window and importing an image. Use any small image; you can find .bmp and .jpg files in your Windows directory.
Add the following code to Class Form2:
Add the following code to Class Form1:
Run the application and click Form1 outside the picture box area. The picture from Form2 appears in the picture box on Form1.
The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it. The GetPicture procedure in Form2 assigns the Image property of the picture box on Form2 to the empty picture box on Form1, and the image from Form2 is displayed on Form1.