简体   繁体   中英

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

Additional information: Object reference not set to an instance of an object."

You should delete this line, before your if statement:

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:

if(fruitBox.SelectedItem != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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