單擊我有兩個單選按鈕對象引用不設置到對象的實例時,我在單選
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.
步驟我也導致了異常:
CarRadioButton
點擊。- 從
ComboBox
- 我點擊
TruckRadioButton
- 得到錯誤採摘 「租賃」:
Object reference not set to an instance of an object
。
任何想法?我認爲它是一個小問題,但我不能發現你爲什麼不上的SelectedItem一個簡單的檢查保護在的SelectedIndexChanged它的代碼:(
您應該先調試 – Matt
您可以使用組合框的Text屬性 'ContractComboBox.Text ==「銷售」' – Jmoreland91
您需要首先檢查'SelectedItem == null',在加載時SelectionChanged事件將會觸發你的表格,所以''加載時,SelectedItem'將爲空。 –