我有两个RadioButtons
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
。有什么想法吗?我认为它有点问题,但我无法发现它:(
答案 0 :(得分:2)
为什么不通过对SelectedItem的简单检查来保护SelectedIndexChanged中的代码?
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;
}
}
}
答案 1 :(得分: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;
}
}
}