2014-03-07 172 views
1

這是我的項目的代碼,您可以在列表框中選擇一個項目,並且會彈出一張圖片和說明。C#:switch語句的問題?

 fruitBox = new ListBox(); 
     fruitImage = new PictureBox(); 

     fruitBox.Items.Add("Mangosteen"); 
     fruitBox.Items.Add("Bael"); 
     fruitBox.Items.Add("Coffee Berries"); 
     fruitBox.Items.Add("Jujube"); 
     fruitBox.Items.Add("Durian"); 

     string selectedFruit; 


    } 

    private void openButton_Click(object sender, EventArgs e) 
    { 
     string selectedFruit; 
     selectedFruit = fruitBox.SelectedItem.ToString(); 

     if (fruitBox.SelectedIndex == -1) 

     { 
      selectedFruit = fruitBox.SelectedItem.ToString(); 

      switch (selectedFruit) 
      { 

       case "Mangosteen": 
        fruitImage.Image = imageList1.Images[0]; 
        fruitDescription.Text = "Mangosteen description"; 
        break; 

       case "Bael": 
        fruitImage.Image = imageList1.Images[1]; 
        fruitDescription.Text = "Bael description"; 
        break; 

       case "Durian": 
        fruitImage.Image = imageList1.Images[2]; 
        fruitDescription.Text = "Durian description"; 
        break; 

       case "Coffee Berries": 
        fruitImage.Image = imageList1.Images[3]; 
        fruitDescription.Text = "Coffee Berries description"; 
        break; 

       case "Jujube": 
        fruitImage.Image = imageList1.Images[4]; 
        fruitDescription.Text = "Jujube description"; 
        break; 
      } 
     } 
     else 
     { 
      MessageBox.Show("Select a fruit"); 

但是當我嘗試運行它,此彈出消息:

「類型‘System.NullReferenceException’未處理的異常發生在異國Fruits.exe

其他信息:對象引用未設置爲對象的實例。「

+0

可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –

回答

1

您應該刪除這條線,你的if語句前:

selectedFruit = fruitBox.SelectedItem.ToString(); 

fruitBox.SelectedItem可能如果沒有SelectedItem。你正在檢查的SelectedIndex但您嘗試訪問SelectedItem之前,讓您的if語句無謂。而且你也可以改變你的if聲明是這樣的:

if(fruitBox.SelectedItem != null) 
+1

另外...如果'SelectedIndex == -1' ...你將會是空的。也許這應該是'!= -1' ...? –

+0

@SimonWhitehead我認爲這樣更安全:) if(fruitBox.SelectedItem!= null)'但你也是。 –