Error "NullReferenceExeption was unhandled" when compiling

-3

Follow the code below:

public partial class Form1 : Form
{
    public Form1()
    {
        button1.Click += Button1_Click;
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        decimal n1, n2, result;

        n1 = Convert.ToInt32(textBox1.Text);
        n2 = Convert.ToInt32(textBox2.Text);

        result = n1 + n2;

        MessageBox.Show("Resultado é " + result.ToString());
    }

}
    
asked by anonymous 08.12.2015 / 00:48

2 answers

4

You have excluded the method InitializeComponent() that should be called in the form constructor. This method is declared in the other part of the class (note that the class has the partial modifier), it is probably in a Form1.Designer.cs file.

Basically, the InitializeComponent() method instantiates and creates all components in your form, so this NullReferenceException is bursting - the button1 variable (like all other components) was not instantiated.

Your builder should look like this:

public Form1()
{
    InitializeComponent();
    button1.Click += Button1_Click;
}

Although it has nothing to do with the error, it is important to say that you do not need to declare your variables as decimal , you can declare them directly as int . This will not cause major problems, but I do not see the sense to do so. If you want to use an integer, create a int variable.

    
08.12.2015 / 11:41
3

Felipe, NullRedferenceExeption occurs when you try to reference an object ( NULO ) that does not exist in your code, if that occurs in that code snippet, it's certainly in textBox1.Text , textBox2.Text , or call Click += new System.EventHandler . Ideally you DEBUG your code and see what those controls have in Text . See More Details Here

See how you can fix this.

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.button1.Click += new System.EventHandler(this.button1_Click);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            decimal n1, n2, result;

            n1 = Convert.ToInt32(textBox1.Text);
            n2 = Convert.ToInt32(textBox2.Text);

            result = n1 + n2;

            MessageBox.Show("Resultado é " + result.ToString());
        }              
    }
    
08.12.2015 / 11:22