C# 引发ArgumentOutOfRange异常
我一直在编写一个Winforms应用程序,其中用户从组合框中选择一些内容。但是,当我运行应用程序时,编译器抛出ArgumentOutOfRange异常,因为索引为-1 代码:C# 引发ArgumentOutOfRange异常,c#,combobox,C#,Combobox,我一直在编写一个Winforms应用程序,其中用户从组合框中选择一些内容。但是,当我运行应用程序时,编译器抛出ArgumentOutOfRange异常,因为索引为-1 代码: if(comboBox1.Enabled==false | | | comboBox2.Enabled==true | | | comboBox3.Enabled==false) { int index=comboBox2.SelectedIndex; string t=comboBox2.Items[index].ToS
if(comboBox1.Enabled==false | | | comboBox2.Enabled==true | | | comboBox3.Enabled==false)
{
int index=comboBox2.SelectedIndex;
string t=comboBox2.Items[index].ToString();//在您的组合框中似乎没有选择任何项。请查看:
当前所选项目的从零开始的索引。如果未选择任何项目,则返回负值(-1)
解决此问题最明显的方法就是在尝试使用某个项目之前检查并确保该项目已被选中,如下所示:
int index = comboBox2.SelectedIndex;
if (index >= 0)
{
string t = comboBox2.Items[index].ToString();
switch (t)
{
...
}
}
您的组合框中似乎没有选择任何项目。请查看:
当前所选项目的从零开始的索引。如果未选择任何项目,则返回负值(-1)
解决此问题最明显的方法就是在尝试使用某个项目之前检查并确保该项目已被选中,如下所示:
int index = comboBox2.SelectedIndex;
if (index >= 0)
{
string t = comboBox2.Items[index].ToString();
switch (t)
{
...
}
}
检查代码何时启动。可能是combo1正在填充,但combo2尚未填充
正如其他人所说,快速方法是测试selectedIndex>=0或selectItem!=null。检查代码何时启动。可能是在填充combo1时,但combo2尚未启动
正如其他人所说,快速方法是测试selectedIndex>=0或selectItem!=null。最好的方法是,将代码放在try-catch块中,您将自己找到答案:)最好的方法是,将代码放在try-catch块中,您将自己找到答案:)