0

I'm using this code to set a picture in Tab.vb from themes.vb:

 Public objForm As Object 'This is at the top of the page, under Public Class

 Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles     RadioButton1.CheckedChanged 
    If RadioButton1.Checked = True Then
        CType(objForm, tab).PictureBox1.Image = Image.FromFile("Abstract.png")


    End If
End Sub

However, when checking the radio button, I get this message:

An unhandled exception of type 'System.NullReferenceException' occurred in REDIEnet Browser.exe

Additional information: Object reference not set to an instance of an object.

Help!

  • 1
    what are `objForm` and `tab`? it looks like you are trying to cast a form to a Tab which will not end well. If the cast fails you end up with Nothing and a NRE. Chop that off, and `PictureBox1.Image = ...` should work fine as long as it is on that form – Ňɏssa Pøngjǣrdenlarp Oct 15 '14 at 23:09
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp Oct 15 '14 at 23:43

1 Answers1

0

With this:

CType(objForm, tab).PictureBox1.Image

it is likely the cast cannot be made (looks like from Form to Tab ?), so the result is Nothing which will cause an NRE.

The title indicates that the PictureBox is on another form. Rather fiddling with the controls on another form, simply provide it with new data and let it do the work:

Public Class FormWithPictureBox

    Private currentFile As String
    Public Sub SetNewImage(filename As String)

       If currentFile <> filename Then
          ' TooDo: check if file exists, clean up
          Me.PictureBox.Image = Image.FromFile(filename)
          currentFile = filename
       End If
    ...

Then, assuming objForm is a valid reference to an instance of FormWithPictureBox:

Public Class OtherForm
    Private Sub RadioButton1_CheckedChanged(...
        If RadioButton1.Checked = True Then
            objForm.SetNewImage(theFileName)
        End If
    End Sub

This allows Forms to take care of their own controls provides a single entry point for other things to instruct it to do something. If/when the time comes when you are trying to figure out why the images changes, you can set a breakpoint in SetNewImage to see who the caller is.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178