-1

I'm trying to catch an error when a value is not selected in the combobox but I cant find whats wrong. There is a CS0136 error but I'm not sure what to do to fix it!

My Code:

        try
        {
            BooksClass.BooksArray[0, 3] = BookCondition.SelectedItem.ToString();
        }
        catch (Exception e)
        {
            MessageBox.Show("Please select an item from the list" + e);
            
        }

Ive tried using a for loop but the System.NullReferenceException: 'Object reference not set to an instance of an object.' error comes up:

 if (string.IsNullOrEmpty(BookCondition.Text))
        {
            MessageBox.Show("Enter a value for The Book Condition:");
        }
        else
        {
            BooksClass.BooksArray[0, 3] = BookCondition.SelectedItem.ToString();
        }
  • Detecting nulls using exception handling is a bad way. Exception catching has a performance penalty. Try not to raise exceptions when you could check if `BookCondition.SelectedItem == null` – Cleptus Apr 24 '21 at 09:35
  • When I use a for loop I have an error: System.NullReferenceException: 'Object reference not set to an instance of an object.' – chefvicious Apr 24 '21 at 09:42
  • if (string.IsNullOrEmpty(BookCondition.Text)) { MessageBox.Show("Enter a value for The Book Condition:"); } else { BooksClass.BooksArray[0, 3] = BookCondition.SelectedItem.ToString(); } – chefvicious Apr 24 '21 at 09:43
  • 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) – Cleptus Apr 24 '21 at 19:29

1 Answers1

0
    if (BookCondition.SelectedItem == null)
    {
        MessageBox.Show("Enter a value for The Book Condition:");
    }
    else
    {
        BooksClass.BooksArray[0, 3] = BookCondition.SelectedItem.ToString();
    }
EldHasp
  • 6,079
  • 2
  • 9
  • 24