-2

I'm trying to do some calculations according to what is selected in the comboboxes but I keep getting System.NullReferenceException: 'Object reference not set to an instance of an object.' as an error.

This is my code, the error appears in the line with the if statement:

private void TokenWorthtxtBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (BookCondition.SelectedItem == null || BookGenre.SelectedItem == null || BookFormat.SelectedItem == null || BookExamBoard.SelectedItem == null)//this is where the error appears
    {
        errormessage.Text = "Please select values from the drop down boxes.";
    }
    else
    {
        int tokenPrice = BookPriceCalculation(BookTitleTxtBox.Text, BookCondition.SelectedItem.ToString(), BookGenre.SelectedItem.ToString(), BookFormat.SelectedItem.ToString(), BookExamBoard.SelectedItem.ToString());
        DisplaySuggestedTokentxtBlock.Text = $"Suggested Token: {tokenPrice}";
    }
}
  • Are you setting/accessing the values before `InitializeComponents()` is called in the constructor? – Jeroen van Langen Apr 24 '21 at 21:39
  • I have already closed your previous question as a duplicate of the canon question ["What is a NullReferenceException and how I fix it"](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). I don't want to repeat the same action against your question, but really, what do you have not understood of the duplicate? – Steve Apr 24 '21 at 21:51
  • No but I am accessing the values in private functions – chefvicious Apr 24 '21 at 21:52
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) @Steve I'll do it for you – Charlieface Apr 24 '21 at 22:07

1 Answers1

0

The objects it controls in the first 'if' can be null, so they end up with '?' Your problem can be solved if you add it.

    if (BookCondition?.SelectedItem == null || BookGenre?.SelectedItem == null || BookFormat?.SelectedItem == null || BookExamBoard?.SelectedItem == null)
    {
        errormessage.Text = "Please select values from the drop down boxes.";
    }
Mico
  • 70
  • 6