您好我有一个代码可以读取文本文件并将内容复制到列表框中。 一切都运行正常,但当我在没有项目的地方点击列表框内部时,会出现一条新的错误消息,并指出我对此行有错误:
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())
如何解决此问题?
答案 0 :(得分:2)
您需要检查所选项目是否为空
if (listBox3.SelectedItem!=null)
{
// write code for it
}
答案 1 :(得分:2)
试图总结每个人所说的话:
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;
}
}
答案 2 :(得分:2)
尝试从ToString()
值调用null
(或任何方法)将产生NRE。如果没有选择任何内容,SelectedItem
将最终成为null
。您必须事先检查null
或使用Convert.ToString()
执行此操作,因为它在给定null
值时不会抛出,它只返回字符串"null"
。
switch (Convert.ToString(listBox3.SelectedItem))
{
// etc...
}
答案 3 :(得分:1)
尝试此修复:
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
}