I'm working on a program, in which on the click of the button a new PictureBox is declared. The problem is, that i'm checking if the PictureBox exists first, using the code

If picCanvas2 Is Nothing Then
       Dim picCanvas2 As New PictureBox
       AddHandler picCanvas2.MouseDown, AddressOf picCanvas2_MouseDown
Else

End If

And with the first line, i get an error saying that picCanvas2 isn't declared. Is there any other way to check if it exists without getting an undeclared error?

Declare your picture box first

Dim picCanvas2 As PictureBox

If picCanvas2 Is Nothing Then
  picCanvas2 = New PictureBox
  AddHandler picCanvas2.MouseDown, AddressOf picCanvas2_MouseDown
Else

End If

of course you have to set picCanvas2's size, position etc. properties too.

Thanks for the help, but on the click of the button, nothing seems to happen. Here's the code...

Dim picCanvas2 As PictureBox
        If picCanvas2 Is Nothing Then
            picCanvas2 = New PictureBox
            Me.Controls.Add(picCanvas2)
            picCanvas2.Size = New Size(500, 400)
            picCanvas2.Location = New Point(144, 112)
            picCanvas2.BackColor = Color.Green
            picCanvas2.Visible = True
        End If

You are missing AddHandler:

picCanvas2 = New PictureBox
  AddHandler picCanvas2.MouseDown, AddressOf picCanvas2_MouseDown

and the handler should be following:

Private Sub picCanvas2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  ' Handle MouseDown event
  If e.Button = Windows.Forms.MouseButtons.Left Then
     MessageBox.Show("Hello from picture", "MouseDown", MessageBoxButtons.OK)
  End If
End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.