2011-06-11 38 views
2

嗨我有一個代碼讀取文本文件並將內容複製到列表框中。 一切工作正常,但是當我在那裏是沒有項目的地方單擊列表框裏面,會出現一個新的錯誤消息,並指出我的財產以後不對這一行:在列表框中沒有任何選擇時出錯

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

什麼是編譯器錯誤? – invalidsyntax 2011-06-11 19:14:59

回答

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 
} 
+0

這會給你錯誤完成開關盒的支架 – 2011-06-11 19:17:58

+0

固定,我從OP – killie01 2011-06-11 19:19:05

+0

複製該問題thanx修復它,你是第一個回答 – 2011-06-11 19:36:00

2

您需要檢查的selectcted項目是空或不是

if (listBox3.SelectedItem!=null) 
{ 

    // write code for it 

} 
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; 
    } 
} 
+0

注意:條件語句的else部分不需要如顯示在選擇的答案中。 – Tim 2011-06-11 20:17:25

2

試圖從null值調用ToString()(或任何方法)值將yie ld NRE的。如果沒有選擇任何內容,SelectedItem將最終成爲null。您需要事先檢查null或使用Convert.ToString()來做到這一點,因爲它在給定null值時不會丟失,它只返回字符串"null"

switch (Convert.ToString(listBox3.SelectedItem)) 
{ 
    // etc... 
} 
相關問題