Click here to Skip to main content
15,920,836 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
See more:
I have been following the tutorial linked below to get an understanding of how to communicate from one form to another using vb.net.
http://www.developerfusion.com/samplechapter/4375/building-windows-applications
For my test application I have a wpf form with an image control and a button control. The image source is set by a 'Loaded' event handler and the button opens another form. On the second form is only a button. When the button's click event is raised I want the image in the first for to change.

I imagine that I am overlooking something simple but here is non-working code so far:
Class MainWindow 
    Public changer As New Window1
    Private Sub Grid1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Grid1.Loaded
        Dim location As String = "pack://application:,,,/movie_ages.png"
        Dim imageresource As New BitmapImage
        imageresource.BeginInit()
        imageresource.UriSource = New Uri(location)
        imageresource.EndInit()
        Image1.Source = imageresource
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        If changer Is Nothing Then
            changer = New Window1
            changer.caller = Me
        End If
        changer.Show()
    End Sub
End Class

Public Class Window1
    Public caller As MainWindow
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        Dim location As String = "pack://application:,,,/Tools.png"
        Dim imageresource As New BitmapImage
        imageresource.BeginInit()
        imageresource.UriSource = New Uri(location)
        imageresource.EndInit()
            caller.Image1.Source = imageresource
    End Sub
End Class


When I run this code I get an error at caller.Image1.Source = imageresource in Pubic Class Window1 stating 'NullReferenceException was unhandled'

Any help would be greatly appreciated.

Thank you,
Jason Self
Posted
Updated 12-May-11 5:27am
v4

1 solution

I would guess you're getting that exception because your definition for changer in MainWindow includes the New keyword, which instantiates it. Then when you check to see if it is Nothing in Button1_Click, it is already instantiated (and therefore not Nothing) and changer.caller never gets set and is therefore Nothing when you try to do something with it in Window1. Remove the New and it'll probably work. (change Public changer As New Window1 to Public changer As Window1)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900