0

Here's code I have written for a simple event based adder, this is the error I constantly get: Object reference not set to an instance of an object.

I am a beginner, so what's my error here? What am I missing? Thanks.

private void txtTwo_TextChanged(object sender, TextChangedEventArgs e)
{
            int numberOne, numberTwo, number3;
            if (int.TryParse(txtOne.Text, out numberOne))
            {
                // DO NOTHING
            }
            else
            {
                MessageBoxButton buttons = MessageBoxButton.OK;
                MessageBoxImage icon = MessageBoxImage.Error;
                MessageBox.Show("Not An Integer! Only Integers Allowed !", "Error : First Number", buttons, icon);
                txtOne.Clear();
            }
            if (int.TryParse(txtTwo.Text, out numberTwo))
            {
                //DO NOTHING
            }
            else
            {
                MessageBoxButton buttons2 = MessageBoxButton.OK;
                MessageBoxImage icon2 = MessageBoxImage.Error;
                MessageBox.Show("Not An Integer! Only Integers Allowed !", "Error : Second Number", buttons2, icon2);
                txtTwo.Clear();
            }

            number3 = numberOne + numberTwo;
            string num3 = number3.ToString();
            txtOut.Text = num3;
}
nvoigt
  • 61,531
  • 23
  • 73
  • 116
Karma.Guy
  • 47
  • 5

2 Answers2

3

In this case it must be txtOut that is null, because num3 has been initialised. Try renaming your txtOut control in the designer or deleting and and recreating it.

Dave Bending
  • 151
  • 2
  • 6
0

So finally got it figured.

Well, num3 can't be null because it's a value type, that means that txt3 is null. txtOut is null because the TextChanged event is raised when txtTwo's Text property is set in XAML which likely happens before the txtOut TextBox is created.

So the solution is to remove the TextChanged event from XAML and put it in the constructor, after InitializeComponent:

public MainWindow() {
    InitializeComponent();
    txtTwo.TextChanged += txtTwo_TextChanged;
}
Karma.Guy
  • 47
  • 5