C#:switch语句有问题吗?

时间:2014-03-07 03:41:17

标签: c# listbox 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'类型的未处理异常

附加信息:对象引用未设置为对象的实例。“

1 个答案:

答案 0 :(得分:1)

您应该在if语句之前删除此行:

selectedFruit = fruitBox.SelectedItem.ToString();
如果没有fruitBox.SelectedItem

SelectedItem可能 null 。您正在检查SelectedIndex但在尝试访问SelectedItem之前使你的if语句毫无意义。你也可以像这样更改if语句:

if(fruitBox.SelectedItem != null)