0

I have a form with a button (btnChoose) and a ListBox (lbxSavedColors) holding hex codes:

My Forms window for context

When I click the Choose button without first selecting a hex code in the listbox, my program crashes on the first line of the button click event with this message:

Object reference not set to instance of object.

System.Windows.Forms.ListBox.SelectedItem.get returned null

My code is below. How can I fix this?

private void btnChoose_Click(object sender, EventArgs e)
{
    Color SelectedColor = System.Drawing.ColorTranslator.FromHtml(lbxSavedColors.SelectedItem.ToString());

    pbxChosenColor.BackColor = SelectedColor;
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794

1 Answers1

2

If you don't have an item selected in the ListBox, then ListBox.SelectedItem will be null. You cannot call .ToString() on null which is why you are getting a NullReferenceException.

You should check that an item is selected before attempting to use ListBox.SelectedItem.

private void btnChoose_Click(object sender, EventArgs e)
{
    if (lbxSavedColors.SelectedItem is null) return;

    Color SelectedColor = System.Drawing.ColorTranslator.FromHtml(lbxSavedColors.SelectedItem.ToString());

    pbxChosenColor.BackColor = SelectedColor;
}
D M
  • 5,769
  • 4
  • 12
  • 27
  • Thanks D M, that solved it. I'm trying to learn code from scratch so I run into many errors wih simple fixes. – Charlie Holm Aug 25 '21 at 13:31
  • If you're just learning, searching the internet for the errors your debugger produces is perhaps one of the best ways to learn. You're unlikely to encounter something novel at the beginning, so you should find many resources explaining what you're seeing and how to fix it. – D M Aug 25 '21 at 13:36