lost_in_the_source
lost_in_the_source

Reputation: 11237

ArgumentOutOfRange Exception thrown

I have been writing a Winforms application, in which the user selects something from a comboBox. However, when I run the application, the compiler throws an ArgumentOutOfRange Exception because the index was -1.

Code:

 if (comboBox1.Enabled == false || comboBox2.Enabled == true || comboBox3.Enabled == false)
        {

            int index = comboBox2.SelectedIndex;
            string t = comboBox2.Items[index].ToString();//<==EXCEPTION
            switch (t)
            {
                case "Ounzes==>Pounds":

                    break;
                case "Pounds==>Ounzes":

                    break;
                case "Tons==>Pounds":
                    break;
                case "Pounds==>Tons":
                    break;
                case "Ounzes==>Tons":
                    break;
                case "Tons==>Ounzes":
                    break;

                case "Stone==>Pound":
                    break;
                case "Pound==>Stone":
                    break;
                case "Tons==>Stone":
                    break;
                case "Stone==>Ton":
                    break;
            }
        }

Can anyone please explain why this exception is being thrown, because I did select something from the comboBox.

Upvotes: 1

Views: 157

Answers (3)

Aster Veigas
Aster Veigas

Reputation: 876

The best thing to do would be,put the code in a try catch block and you'll find out answers for yourself :)

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Check when your code is firing. Might be when combo1 is being populated, but combo2 hasn't yet.

As others have said quick way is to test selectedIndex >= 0 or selectItem != null.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149020

It appears that no item was selected in your ComboBox. Take a look at the documentation:

A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.

The most obvious way to fix this is just to check to make sure an item has been selected before you try to use it, like this:

int index = comboBox2.SelectedIndex;
if (index >= 0)
{
    string t = comboBox2.Items[index].ToString();
    switch (t)
    {
        ...
    }
}

Upvotes: 4

Related Questions