在列表框中不选择任何内容时出错

本文关键字:任何内 出错 选择 列表 | 更新日期: 2023-09-27 17:58:52

嗨,我有一个代码可以读取文本文件并将内容复制到列表框中。一切都很好,但当我在没有项目的地方点击列表框时,会出现一条新的错误消息,它指出我这行有点问题:

switch (listBox3.SelectedItem.ToString()) {
    case "Accessories":
        label4.Text = "None Required"; //Approval
        label13.Text = " "; //Approval
        label5.Text = "TTS";  //sent by
        label6.Text = "IT Co.";   //sender
        label7.Text = "2";  //urgent
        label8.Text = "3";  //normal
        label9.Text = "PC Name";   // required filed 1
        label10.Text = "PC Brand && Model";  // required filed 2
        label11.Text = "B.C";  // required filed 3
        label12.Text = "Location";  // required filed 4
        label14.Text = "User Name";  // required filed 5
    break;

这只是一段代码,编译器指出的行是:

switch (listBox3.SelectedItem.ToString())

如何解决此问题?

在列表框中不选择任何内容时出错

您需要检查所选项目是否为空

if (listBox3.SelectedItem!=null)
{
  // write code for it 
}

尝试从null值调用ToString()(或任何方法)将产生NRE。如果没有选择任何内容,则CCD_ 3将最终成为CCD_。您必须事先检查null,或者使用Convert.ToString()来执行此操作,因为当给定null值时,它不会抛出,它只返回字符串"null"

switch (Convert.ToString(listBox3.SelectedItem))
{
    // etc...
}

试图总结每个人所说的话:

if(listBox3.SelectedItem != null) {
    switch (listBox3.SelectedItem.ToString()) {
        case "Accessories":
            label4.Text = "None Required"; //Approval
            label13.Text = " "; //Approval
            label5.Text = "TTS";  //sent by
            label6.Text = "IT Co.";   //sender
            label7.Text = "2";  //urgent
            label8.Text = "3";  //normal
            label9.Text = "PC Name";   // required filed 1
            label10.Text = "PC Brand && Model";  // required filed 2
            label11.Text = "B.C";  // required filed 3
            label12.Text = "Location";  // required filed 4
            label14.Text = "User Name";  // required filed 5
        break;
    }
}

尝试此修复程序:

if(listBox3.SelectedItem != null) {
    switch (listBox3.SelectedItem.ToString()) {
        case "Accessories":
            label4.Text = "None Required"; //Approval
            label13.Text = " "; //Approval
            label5.Text = "TTS";  //sent by
            label6.Text = "IT Co.";   //sender
            label7.Text = "2";  //urgent
            label8.Text = "3";  //normal
            label9.Text = "PC Name";   // required filed 1
            label10.Text = "PC Brand && Model";  // required filed 2
            label11.Text = "B.C";  // required filed 3
            label12.Text = "Location";  // required filed 4
            label14.Text = "User Name";  // required filed 5
        break;
    }
}
else {
    //nothing selected
}