Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ListBox Selected Item Null Exception

The user can click an item in a ListBox as follows:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    textBox2.Clear();
    listBox2.Items.Clear();

    string[] p = 
         Directory.GetFiles(
             textBoxDir.Text, 
             listBox1.SelectedItem.ToString(),
             SearchOption.AllDirectories);

    foreach (string open in p) 
        ......
}

All is fine. However if the user clicks on an empty space in the ListBox, it displays the following error:

System.NullReferenceException

This is because of this line of code:

string[] p = 
    Directory.GetFiles(
        textBoxDir.Text, 
        listBox1.SelectedItem.ToString(),   
        SearchOption.AllDirectories);

Does anyone have a clever work around? Or suggest an aalternative to my code?

like image 510
Nigel.Harris Avatar asked Dec 02 '22 23:12

Nigel.Harris


2 Answers

The workaround is to check for a null value, and exit early.

if (listBox1.SelectedItem == null)
{
    return;
}

This avoids the nesting introduced by the other answers, which makes the code less readable.

like image 73
devdigital Avatar answered Dec 22 '22 02:12

devdigital


You can check SelectedIndex before that line:

if(listBox2.SelectedIndex < 0)
    return;
like image 43
Hossein Narimani Rad Avatar answered Dec 22 '22 02:12

Hossein Narimani Rad