codingguy3000
codingguy3000

Reputation: 2835

Getting a NullReferenceException Error when invoking a Select File Dialog Box

This is a real newbie question. I have simple app that selects a picture and display's that picture in a PictureBox.

I decided to mess with the Opacity Attribute so I added a timer and created this cool effect where the Main Form's Opacity is increased by 20% every 400 miliseconds.

The problem is that now when I click the button that invokes the Select File Dialog Box I'm getting a NullReferenceException error.

 private void tmrClock_Tick(object sender, EventArgs e)
    {
        if (ViewerForm.ActiveForm.Opacity != 1)
        {
        ActiveForm.Opacity = ActiveForm.Opacity + .20;
        }
    }

The error message is pointing to the if statement.

What am I doing wrong?

Thanks

Upvotes: 1

Views: 547

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292425

When you show a modal dialog, your form is not active anymore. So ActiveForm is the modal dialog, which is not a Form (it's a native window), so ActiveForm returns null.

Why don't you refer to the Form itself rather than the ActiveForm ?

private void tmrClock_Tick(object sender, EventArgs e)
{
    if (this.Opacity != 1)
    {
        this.Opacity = ActiveForm.Opacity + .20;
    }
}

Upvotes: 2

SLaks
SLaks

Reputation: 887413

The ActiveForm property returns the Form object that is currently focused.

When you open a file dialog, there is focused form is not a managed Form object, so ActiveForm returns null.

Assuming that your timer is inside your form, you should simply write this.Opacity. The this keyword refers to the Form object that the timer is in.

By the way, you should stop your timer when the animation finishes (by calling tmrClock.Stop())

Upvotes: 3

Related Questions