locked
System.NullReferenceException When transferring data RRS feed

  • Question

  • I have two windows open and I am trying to transfer text from a text box on page 1 to a password box on page 2. It's really baffling me, because it was working perfectly before and it's now giving me a System.NullReferenceException:

    MainWindow mainWindow = Application.Current.MainWindow as MainWindow;
                mainWindow.passBox1.Password = this.genBox.Text;
                mainWindow.passBox2.Password = this.genBox.Text;


    This is the error I receive:

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

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

    -

    Does anybody know what could be causing this? Like I said, it was working perfectly before, I just tried it and now it's giving me this error.

    Thanks.

    Friday, December 20, 2013 4:00 PM

Answers

  • To avoid error you should have a null check too

    MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    if (mainWindow != null)
    {
      mainWindow.passBox1.Password = this.genBox.Text;
      mainWindow.passBox2.Password = this.genBox.Text;
    }


    Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor


    Friday, December 20, 2013 6:59 PM

All replies

  • Okay, I have figured out the problem, it is because I have changed the start up Window. So how do I make this code work? 
    Friday, December 20, 2013 4:04 PM
  • You could use the Application.Current.Windows property:

    MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    mainWindow.passBox1.Password = this.genBox.Text;
    mainWindow.passBox2.Password = this.genBox.Text;
    

    Friday, December 20, 2013 5:30 PM
  • To avoid error you should have a null check too

    MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    if (mainWindow != null)
    {
      mainWindow.passBox1.Password = this.genBox.Text;
      mainWindow.passBox2.Password = this.genBox.Text;
    }


    Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor


    Friday, December 20, 2013 6:59 PM