[英]C#: Problems with switch statement?
這是我的項目的代碼,您可以在其中選擇列表框中的項目,然后會彈出圖片和說明。
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");
但是,當我嘗試運行它時,會彈出此消息:
“ Exotic Fruits.exe中發生了'System.NullReferenceException類型的未處理的異常。
附加信息:對象引用未設置為對象的實例。”
您應該在if語句之前刪除此行:
selectedFruit = fruitBox.SelectedItem.ToString();
如果沒有SelectedItem
fruitBox.SelectedItem
可能為null 。您正在檢查SelectedIndex
但是在嘗試訪問SelectedItem
,這會使if語句毫無意義 。您還可以像下面這樣更改if
語句:
if(fruitBox.SelectedItem != null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.