Skip to main content
 首页 » 编程设计

c#之抛出 ArgumentOutOfRange 异常

2024年02月13日12dflying

我一直在编写一个 Winforms 应用程序,用户可以在其中从组合框中选择内容。但是,当我运行该应用程序时,编译器会抛出 ArgumentOutOfRange 异常,因为索引为 -1。

代码:

 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; 
            } 
        } 

任何人都可以解释为什么抛出这个异常,因为我确实从组合框中选择了一些东西。

请您参考如下方法:

您的 ComboBox 中似乎没有选择任何项目。看看 documentation :

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

解决这个问题最明显的方法就是检查以确保在尝试使用项目之前已选择它,如下所示:

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