"Nullreferenceexeption error was unhandled" when compiling

Asked

Viewed 63 times

-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());
    }

}
  • 2

    In which line? Only with this excerpt can not identify where the problem is. This error is symptom of problem elsewhere. By the way, you’re not in trouble at Visual Studio, understand: http://answall.com/a/101703/101

2 answers

4


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

Basically the method InitializeComponent() instancia and creates all the components in your form, so this NullReferenceException is popping - the variable button1 (as all other components) were not instantiated.

Your builder should stay 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 won’t cause big problems, but I don’t see the point to do it. If you want to use an integer create a variable int.

3

Felipe, the NullRedferenceExeption occurs when you try to reference an object (NULO) that does not exist in your code, if this occurs in this code snippet is surely in textBox1.Text, textBox2.Text or on the call from Click += new System.EventHandler. the ideal is you DEBUG your code and see what these controls have on Text. See more details here

See how you can fix it.

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());
        }              
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.