mafap
mafap

Reputation: 391

ComboBox Exception when items are not selected

I have a ComboBox with several items and a button that have the focus of the Form. The problem is that I need to change the SelectedItem or I will get a NullReferenceException.

comboBox.Text = "select";

try
{
    //if (comboBox.SelectedIndex == -1) return;

    string some_str = comboBox.SelectedItem.ToString(); // <-- Exception

    if (some_str.Contains("abcd"))
    {
        // ...
    }
}
catch (Exception sel)
{
    MessageBox.Show(sel.Message);
}

Is there any way to avoid that? If I use if (comboBox.SelectedIndex == -1) return; I don't get any error but my button also doesn't work.

Upvotes: 0

Views: 5738

Answers (1)

Nemanja Boric
Nemanja Boric

Reputation: 22157

Well, if SelectedItem is null, and you try to call ToString() on the null reference, you will get NullReferenceException.

You need to check for the null, before running ToString():

string some_str = combBox.SelectedItem == null ? String.Empty : comboBox.SelectedItem.ToString(); // <-- Exception

if (some_str.Contains("abcd"))
{
    // ...
}

or

if(comboBox.SelectedItem != null)
{
    string some_str = comboBox.SelectedItem.ToString(); // <-- Exception

    if (some_str.Contains("abcd"))
    {
        // ...
    }
}
else
{
     MessageBox.Show("Please select an item");
}

Upvotes: 3

Related Questions