2013-05-01 29 views
0

下面是我爲基於事件的簡單加法器編寫的代碼,這是我經常得到的錯誤:未將對象引用設置爲對象的實例。System.NullReferenceException處理

我是初學者,所以我的錯誤是什麼?我錯過了什麼?謝謝。

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; 
} 
+3

正是你在哪裏得到的例外呢? – 2013-05-01 09:55:40

+0

什麼是例外? – 2013-05-01 09:57:04

+1

最後一行:txtOut.Text = num3; 我很困惑它爲什麼拋出異常。 – 2013-05-01 09:58:11

回答

0

所以最後弄明白了。

那麼,num3不能爲null,因爲它是一個值類型,這意味着txt3爲null。 txtOut爲null,因爲在XAML中設置txtTwo的Text屬性時可能會發生TextChanged事件,這可能發生在txtOut TextBox創建之前。

所以解決的辦法就是從XAML中刪除TextChanged事件,並把它的構造,之後的InitializeComponent:

public MainWindow() { 
    InitializeComponent(); 
    txtTwo.TextChanged += txtTwo_TextChanged; 
} 
3

在這種情況下,它必須是txtOut是空的,因爲num3已初始化。嘗試在設計器中重命名您的txtOut控件,或者刪除並重新創建它。

+0

仍顯示相同的錯誤! – 2013-05-01 10:08:52

相關問題