HelpNeeder
HelpNeeder

Reputation: 6480

An error while choosing option from DialogResult

I am experiencing a problem while choosing Yes on my MessageBox with buttons Yes or No.

Object reference not set to an instance of an object.

From line:

AddEntryWindow addWindow = new AddEntryWindow
    (this, storedAuth.UserName, storedAuth.Password);

I don't understand what's the problem since few lines after this, is the same statement. How can I fix this?

Fixed

private void tsmiAddEntry_Click(object sender, EventArgs e)
{
    if (storedAuth == null)
    {
        DialogResult result = MessageBox.Show
            ("You must log in before you add an entry." 
            + Environment.NewLine + "You want to authenticate?",
            "Information", MessageBoxButtons.YesNo, 
            MessageBoxIcon.Information);

        if (result == DialogResult.Yes)
        {
            AuthenticationWindow authWindow = 
                new AuthenticationWindow();
            authWindow.ShowDialog();
            storedAuth = authWindow.Result;

            AddEntryWindow addWindow = new AddEntryWindow
                (this, storedAuth.UserName, storedAuth.Password);
            addWindow.ShowDialog();
        }
    }
    else
    {
        AddEntryWindow addWindow = new AddEntryWindow
            (this, storedAuth.UserName, storedAuth.Password);
        addWindow.ShowDialog();
    }
}

Upvotes: 0

Views: 200

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Look this statement if (storedAuth == null)

and you accessing property of a null object. if it is necessary object then assign value to this object then access UserName and Password.

this is reason of error.. you should not use storedAuth.UserName, storedAuth.Password) in the following statement. use some default value like "" or "Default"

AddEntryWindow addWindow = new AddEntryWindow (this, storedAuth.UserName, storedAuth.Password); addWindow.ShowDialog();

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292455

You're accessing properties of storedAuth, but just above you checked that storedAuth is null, so this code is guaranteed to throw a NullReferenceException...

Upvotes: 2

Related Questions