none
TextChanged - System.NullReferenceException Problem RRS feed

  • Question

  • Here's code I have written for a simple event based multiplier , this is the error I constantly get: Object reference not set to an instance of an object at this line: txt3.Text = num3.ToString();.
    I am a beginner, so what's my error here? What am I missing? Thanks. All the TextBoxes have value set in XAML.


    Here's code I have written for a simple event based multiplier , this is the error I constantly get: Object reference not set to an instance of an object at this line: txt3.Text = num3.ToString();.
    I am a beginner, so what's my error here? What am I missing? Thanks. All the TextBoxes have value set in XAML.

    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            private void txt2_TextChanged(object sender, TextChangedEventArgs e)
            {
                int num1, num2, num3;
                num1 = int.Parse(txt1.Text);
                num2 = int.Parse(txt2.Text);
                num3 = num1 * num2;
                txt3.Text = num3.ToString();
            }
        }


    Wednesday, May 1, 2013 11:00 AM

Answers

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

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

    public MainWindow() {
        InitializeComponent();
        txt2.TextChanged += txt2_TextChanged;
    }

    • Marked as answer by Debojyoti Das Wednesday, May 1, 2013 11:19 AM
    Wednesday, May 1, 2013 11:13 AM
    Moderator

All replies

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

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

    public MainWindow() {
        InitializeComponent();
        txt2.TextChanged += txt2_TextChanged;
    }

    • Marked as answer by Debojyoti Das Wednesday, May 1, 2013 11:19 AM
    Wednesday, May 1, 2013 11:13 AM
    Moderator
  • Thanks ! Problem Solved ! You are awesome :D
    Wednesday, May 1, 2013 11:19 AM