C#索引超出了数组[combox]的界限

本文关键字:combox 界限 数组 索引 | 更新日期: 2023-09-27 18:24:34

下面是我开始调试时导致错误的代码。当我从combobox1或combobox2中选择选项时,我收到一条弹出消息:索引超出了数组的范围。我该如何解决这个问题?

感谢您抽出时间阅读。:)

public Form1()
{
    InitializeComponent();
    String[] arr1 = new String[2];
    arr1[0] = "SG";
    arr1[1] = "MY";
    comboBox1.Items.AddRange(arr1);
    comboBox2.Items.AddRange(arr1);        
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    double[,] arr = new double[2, 2];
    for(int i = 0; i <2; i++)
    {            
        arr[0, 0] = 1;
        arr[0, 1] = 1.24;
        arr[1, 0] = 0.80;
        arr[1, 1] = 1;
        label1.Text = 
            arr[comboBox1.SelectedIndex,
                comboBox2.SelectedIndex].ToString();//Index was outside the bounds of the array.         
    }
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{           
    double[,] arr = new double[2, 2];
    for(int i = 0; i < 2; i++)
    {
        arr[0, 0] = 1;
        arr[0, 1] = 1.24;
        arr[1, 0] = 0.80;
        arr[1, 1] = 1;
        label1.Text = 
            arr[comboBox1.SelectedIndex,
                comboBox2.SelectedIndex].ToString();//Index was outside the bounds of the array.
    }
}

C#索引超出了数组[combox]的界限

您应该在调试模式下逐步完成它。但我想这是因为其中一个组合框没有选定的值,因此SelectedIndex返回的是-1,这是无效的。

您可以在每个事件开始时添加一个验证检查,以查看两个组合框是否都选择了值。或者更好的是,使用一个通用函数:

void CreateArray()
{
    //could also validate the values are not greater than 1 if you think that is worth it
    if(comboBox1.SelectedIndex == -1 || comboBox2.SelectedIndex == -1)
        return;
    double[,] arr = new double[2, 2];
    for(int i = 0; i < 2; i++)
    {
        arr[0, 0] = 1;
        arr[0, 1] = 1.24;
        arr[1, 0] = 0.80;
        arr[1, 1] = 1;
        label1.Text = arr[comboBox1.SelectedIndex, comboBox2.SelectedIndex].ToString();//Index was outside the bounds of the array.
    }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    CreateArray();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    CreateArray();
}
//or subscribe both events to the same handler

在这种情况下,只有在设置了bot组合框值后,才会填充label1。或者,您也可以先将每个组合框设置为具有默认值。取决于您的实际需求。


其他注意事项:

  • 您的for loop似乎毫无用处。你只是做了两次完全相同的事情
  • 最好创建一次数组,而不是每次创建一次。创建一个类级变量来保存数组(Sayse的回答中实际演示了这一点)

这在一定程度上是一个离题的答案,但请考虑以下内容。。

private double[,] arr = new double[2,2]{{1,1.24},{0.80, 1}};
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
     if(comboBox1.SelectedIndex == -1 || comboBox2.SelectedIndex == -1)
        return;
     label1.Text = arr[comboBox1.SelectedIndex, comboBox2.SelectedIndex].ToString();
}

您甚至可以将此事件用于两个组合框

ComboBox中没有任何选择时,其SelectedIndex可能会变为-1。我建议您首先检查SelectedIndex是否不是-1,或者将其规范化,以便如果是-1,则将其视为0。