Object reference not set to an instance of an object in splashform

777 views Asked by At

I wanted my program to show a loading message while it checks if the program has connected to a device... but i get an error when i try to close the splashform using the code

SplashForm.CloseForm();

the actual splashform code is...

class SplashForm
{
    //Delegate for cross thread call to close
    private delegate void CloseDelegate();

    //The type of form to be displayed as the splash screen.
    private static SplashForm splashForm;

    static public void ShowSplashScreen()
    {
        // Make sure it is only launched once.

        if (splashForm != null)
            return;
        Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm));
        thread.IsBackground = true;
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();           
    }

    static private void ShowForm()
    {
        splashForm = new SplashForm();
        Application.Run(splashForm);
    }

    static public void CloseForm()
    {
        splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));
    }

    static private void CloseFormInternal()
    {
        splashForm.Close();
    }
...
}

in this code... I get a error message as "Object reference not set to an instance of an object" at the line

 splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));

what is the reason and solution?

1

There are 1 answers

0
James Ko On

The Object reference not set to an instance of an object message is the trademark of the NullReferenceException. Here, it means that your splashForm field is null.

Make sure that you have 1) called SplashForm.ShowSplashScreen() before you call SplashForm.CloseForm() and 2) consider calling thread.Join() in ShowSplashScreen() so you can be sure that by the time you leave that method, splashForm is not null.