C#ListBox选择项目空例外

Nig*_*ris 2 c# listbox nullreferenceexception

用户可以单击ListBox中的项目,如下所示:

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) 
        ......
}
Run Code Online (Sandbox Code Playgroud)

一切都很好.但是,如果用户单击ListBox中的空白区域,则会显示以下错误:

System.NullReferenceException
Run Code Online (Sandbox Code Playgroud)

这是因为这行代码:

string[] p = 
    Directory.GetFiles(
        textBoxDir.Text, 
        listBox1.SelectedItem.ToString(),   
        SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)

有没有人有聪明的工作?或者建议我的代码替代?

dev*_*tal 8

解决方法是检查空值,并提前退出.

if (listBox1.SelectedItem == null)
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

这避免了其他答案引入的嵌套,这使得代码的可读性降低.