2014-02-27 41 views
0

單擊我有兩個單選按鈕對象引用不設置到對象的實例時,我在單選

private void CarRadioButton_Checked(object sender, RoutedEventArgs e) 
     { 
      try 
      { 

       // When CarRadioButton is clicked. "Leasing" and "Sale" is added 
        to Combobox 

       ContractComboBox.Items.Clear(); 

       ContractComboBox.Items.Add("Leasing"); 
       ContractComboBox.Items.Add("Sale"); 


      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

     } 

     private void TruckRadioButton_Checked(object sender, RoutedEventArgs e) 
     { 
      try 
      { 
       // When TruckRadioButton is clicked. "Leasing" is added 
        to Combobox 

       ContractComboBox.Items.Clear(); 

       ContractComboBox.Items.Add("Leasing"); 

      } 
      catch (Exception ex) 
      { 
      MessageBox.Show(ex.Message); 
      } 

     } 

當我選擇從ComboBox一個項目,我想要做的事,像下面這樣:

private void ContractComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      if (ContractComboBox.SelectedItem.ToString() == "Leasing") 
      { 
       PriceMonthTextBox.IsEnabled = true; 
       PeriodTextBox.IsEnabled = true; 
      } 

      if (ContractComboBox.SelectedItem.ToString() == "Sale") 
      { 
       PriceMonthTextBox.IsEnabled = false; 
       PeriodTextBox.IsEnabled = false; 
      } 

     }  

現在,這是我的問題。如果我從ComboBox並在另一個RadioButton是點擊後選擇一個項目,我得到一個錯誤:Object reference not set to an instance of an object.

步驟我也導致了異常:

  1. CarRadioButton點擊。
  2. ComboBox
  3. 我點擊TruckRadioButton
  4. 得到錯誤採摘 「租賃」:Object reference not set to an instance of an object

任何想法?我認爲它是一個小問題,但我不能發現你爲什麼不上的SelectedItem一個簡單的檢查保護在的SelectedIndexChanged它的代碼:(

+0

您應該先調試 – Matt

+0

您可以使用組合框的Text屬性 'ContractComboBox.Text ==「銷售」' – Jmoreland91

+0

您需要首先檢查'SelectedItem == null',在加載時SelectionChanged事件將會觸發你的表格,所以''加載時,SelectedItem'將爲空。 –

回答

2

private void ContractComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (ContractComboBox.SelectedItem != null) 
    { 
     if (ContractComboBox.SelectedItem.ToString() == "Leasing") 
     { 
      PriceMonthTextBox.IsEnabled = true; 
      PeriodTextBox.IsEnabled = true; 
     } 

     if (ContractComboBox.SelectedItem.ToString() == "Sale") 
     { 
      PriceMonthTextBox.IsEnabled = false; 
      PeriodTextBox.IsEnabled = false; 
     } 
    } 
}  
0

試試這個:

private void ContractComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
     if(ContractComboBox.SelectedIndex >= 0) 
     { 
     if (ContractComboBox.SelectedItem.ToString() == "Leasing") 
     { 
      PriceMonthTextBox.IsEnabled = true; 
      PeriodTextBox.IsEnabled = true; 
     } 

     if (ContractComboBox.SelectedItem.ToString() == "Sale") 
     { 
      PriceMonthTextBox.IsEnabled = false; 
      PeriodTextBox.IsEnabled = false; 
     } 
     } 
} 
相關問題