1

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."

  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Rowland Shaw Apr 12 '14 at 20:59

1 Answers1

1

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)
Selman Genç
  • 94,267
  • 13
  • 106
  • 172