繁体   English   中英

C#索引不在数组[combobox]的范围内

[英]C# Index was outside the bounds of the array [combobox]

以下是我开始调试时导致错误的代码。 当我从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.
    }
}

您应该在调试模式下逐步执行。 但是我想这是因为您的ComboBoxes之一没有选定的值,因此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 ComboBox值后,才会填充label1 或者,您也可以将每个ComboBox设置为首先具有默认值。 取决于您的实际需求。


其他一些注意事项:

  • 您的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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM