2 Replies - 312 Views - Last Post: 01 May 2013 - 05:40 AM Rate Topic: ***-- 2 Votes

#1 Jeet.in  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 304
  • Joined: 30-May 11

System.NullReferenceException Handled

Posted 01 May 2013 - 03:41 AM

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



Where have I gone wrong?

This post has been edited by Jeet.in: 01 May 2013 - 03:44 AM


Is This A Good Question/Topic? 0
  • +

Replies To: System.NullReferenceException Handled

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3449
  • View blog
  • Posts: 10,643
  • Joined: 05-May 12

Re: System.NullReferenceException Handled

Posted 01 May 2013 - 05:38 AM

Show us the XAML.
Was This Post Helpful? 1
  • +
  • -

#3 Jeet.in  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 304
  • Joined: 30-May 11

Re: System.NullReferenceException Handled

Posted 01 May 2013 - 05:40 AM

Already solved it. Thank you for your reply though :)

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 !

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

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1