The NullReferenceException was unhandled, the Object Reference was not set to the object instance

Whenever I run my program, I get: NullReferenceException was unhandled, the Object Reference was not installed in the object instance.

When I run the program, I have a form called MaxScore, where the user enters the maximum score and clicks OK. In the OK event, I call a method from MainForm to update maxGameCountLabel to MainForm with the value entered for the maximum value as a parameter.

When I click ok, I get a NullReferenceException in

myGameCountLbl.Text = maxGames.ToString();

of my maxGameCountLblUpdate method.

Here is the code for the maxGameCountLblUpdate method, which is located in MainForm:

//Update game count label 
public void maxGameCountLblUpdate(decimal maxGames)
{
    maxGames = decimal.ToInt32(maxGames);
    myGameCountLbl.Text = maxGames.ToString();
    compGameCountLbl.Text = maxGames.ToString();
}

Here is my OK Button event at MaxScore:

private void okBtn_Click(object sender, EventArgs e)
{
    MainForm.maxGameCountLblUpdate(max);
}

Notice i set

public Form1 MainForm { get; set; }

at MaxScore

MaxScore MainForm :

    using (MaxScore scoreForm = new MaxScore())
    {
        scoreForm.MainForm = this;
        scoreForm.ShowDialog();
    }

. . !

EDIT: myGameCountLbl.Text = maxGames.ToString(); myGameCountLbl, , null... , ... ? maxGames, , 1,

+3
5

: InitializeComponent(); ?

, Visual Studio (Class.designer.cs) . InitializeComponent() , NullReferenceException.

+2

, , :

myGameCountLbl.Text = maxGames.ToString();

myGameCountLbl null, maxGames is. , maxGames , , myGameCountLbl null.

, ? myGameCountLbl?

+4

Visual Studio NullReferenceExceptions, , .

( → → Runtime...)

+1

? ?

MainForm.maxGameCountLblUpdate();

0

, , , .

, :

, .

. IF, , , :

if (maxGames!=null){
      myGameCountLbl.Text = maxGames.ToString();
}

myGameCounLbl

,

0

Source: https://habr.com/ru/post/1708379/


All Articles