B
B
BadCats2017-06-22 12:31:46
WPF
BadCats, 2017-06-22 12:31:46

NullReferenceException when comparing contents of ComboBoxItem?

private void ComboBoxMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            ComboBoxItem lbi = ((sender as ComboBox).SelectedItem as ComboBoxItem); 
 
           
         
            
            if (lbi.Content.ToString()=="Вийти из приложения")

and here on this line: throws an exception
if (lbi.Content.ToString()=="Вийти из приложения")
System.NullReferenceException: "Object reference does not point to an instance of an object."

- but in the sense of an instance of an object? I'm working with SelectedItem - a property that I cast to ComboBoxItem with as - and passing all this to lbi , but I can't pass a link to a new instance, because I'm already working with the current ComboBox and its ComboBoxItem ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlov, 2017-06-22
@BadCats

ComboBoxItem lbi = ((sender as ComboBox).SelectedItem as ComboBoxItem);

The variable lbican contain nullif nothing is selected, because asreturns nullif the conversion failed.
Below you are trying to access the Contenty field null. The compiler reports this.
Solution: you need to add a check for nullbefore uselbi

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question