I have created two comboboxes, one for the min value and one for the max value. My code should make sure the user doesn’t select a min value greater than the max value, or a max value smaller than the min value using this code.
private void MaxRating_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
switch (MaxRating.SelectedIndex)
{
case 0:
if (MinRating.SelectedIndex > 0)
MinRating.SelectedIndex = 0;
break;
case 1:
if (MinRating.SelectedIndex > 1)
MinRating.SelectedIndex = 1;
break;
case 2:
if (MinRating.SelectedIndex > 2)
MinRating.SelectedIndex = 2;
break;
case 3:
if (MinRating.SelectedIndex > 3)
MinRating.SelectedIndex = 3;
break;
case 4:
if (MinRating.SelectedIndex > 4)
MinRating.SelectedIndex = 4;
break;
}
}
However when debugging at the line where it says “if (MinRating.SelectedIndex > 0)” I get “NullReferenceException was unhandled by user code”.
I’m not sure why, I also have a function for MinRating_SelectionChanged, and I don’t seem to be getting anything like that there.
If I remove case:0 from this function, there seems to be no errors. Not from the other function either. I also tried replacing > with == but it just seems to do the same thing.
Any help would be appereciated because I’m just confused.
EDIT: if I just place these two lines
int minrating = MinRating.SelectedIndex;
int maxrating = MaxRating.SelectedIndex;
it gives the error at the second line
If carefully analyze, you will see this method may be called even during initialization of the controls, where
MaxRatinghas just been constructed butMinRatingis not even constructed. You cannot assume both of them are constructed when this method is called.You might check against null for both of them at the beginning of this method as a workaround.