這是我的項目的代碼,您可以在列表框中選擇一個項目,並且會彈出一張圖片和說明。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
其他信息:對象引用未設置爲對象的實例。「
可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –