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?
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.
You can check SelectedIndex
before that line:
if(listBox2.SelectedIndex < 0)
return;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With