简体   繁体   English

C#:switch语句有问题吗?

[英]C#: Problems with switch statement?

This is the code for my project where you select an item in a listbox, and a picture along with a description will pop up. 这是我的项目的代码,您可以在其中选择列表框中的项目,然后会弹出图片和说明。

        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");

But when I try to run it, this message pops up: 但是,当我尝试运行它时,会弹出此消息:

"An unhandled exception of type 'System.NullReferenceException' occurred in Exotic Fruits.exe “ Exotic Fruits.exe中发生了'System.NullReferenceException类型的未处理的异常。

Additional information: Object reference not set to an instance of an object." 附加信息:对象引用未设置为对象的实例。”

You should delete this line, before your if statement: 您应该在if语句之前删除此行:

selectedFruit = fruitBox.SelectedItem.ToString();

fruitBox.SelectedItem might be null if there is no SelectedItem .You are checking the SelectedIndex but before you try to access SelectedItem and that makes your if statement pointless .And also you can change your if statement like this: 如果没有SelectedItem fruitBox.SelectedItem可能为null 。您正在检查SelectedIndex但是在尝试访问SelectedItem ,这会使if语句毫无意义 。您还可以像下面这样更改if语句:

if(fruitBox.SelectedItem != null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM