-1

I am loading image deshBoardForm to CurrentForm through button.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DeveloperHeaderPictureBox.Image = DeshBoard.HeaderPictureBox.Image
End Sub

But there is an error:

An unhandled exception of type 'System.NullReferenceException' occurred in Microsoft.VisualBasic.dll Additional information: Object variable or With block variable not set.

djv
  • 11,577
  • 7
  • 43
  • 62
  • If `deshBoardForm` is the instance which you want to use its image, you need to instantiate `deshBoardForm` then change your code to `DeveloperHeaderPictureBox.Image = deshBoardForm.HeaderPictureBox.Image` – selfstudy Sep 17 '18 at 13:16
  • `DeshBoard` is the name of `deshBoardForm` – Waqar YousufZai Sep 17 '18 at 13:19
  • Which of `DeshBoard` and `deshBoardForm` is the classname, and which is the instance? Can you show the code which declares the instance? – djv Sep 17 '18 at 14:47

1 Answers1

0

There are two ways to access a form in VB.Net. One is not recommended.

The non-recommended way is to use the default form instance in VB.NET (see this answer for an explanation)

' Assuming DeshBoard is the name of the class

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DeveloperHeaderPictureBox.Image = DeshBoard.HeaderPictureBox.Image
End Sub

Image is accessed via

  • DeshBoard: if no instance, create one, return
  • HeaderPictureBox: a new PictureBox is created with the instance, is returned
  • Image: may be Null, is returned (this is OK)

Most likely, this method is actually safer in terms of not having run-time errors, because if no instance exists, one is created for you. But it's not always what you want. For instance, if an explicit instance is used elsewhere, you aren't guaranteed to use the same instance in both places.

It is recommended to not use the default form instance, and to create an explicit instance instead.

Private myDeshBoard As New DeshBoard()

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    DeveloperHeaderPictureBox.Image = myDeshBoard.HeaderPictureBox.Image
End Sub

In this case you create an instance which lives inside the main form. You may want to create it elsewhere such as a factory or singleton, so the same instance is accessed everywhere. (that is outside the scope of this question)

An issue would arise when you declare the instance such as:

Private myDeshBoard As DeshBoard() ' notice the missing "New"

then the instance would have never been created, and accessing any property of a Null reference would raise the exception you experienced.

Image is accessed via

  • myDeshBoard: if no instance, exception, else return
  • HeaderPictureBox: a new PictureBox is created with the instance, is returned
  • Image: may be Null, is returned (this is OK)
djv
  • 11,577
  • 7
  • 43
  • 62