I have a form with a button (btnChoose
) and a ListBox (lbxSavedColors
) holding hex codes:
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;
}