0

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

感谢您花时间阅读。:)

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.
    }
}
4

3 回答 3

7

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

您可以在每个事件开始时添加验证检查,以查看两个 ComboBox 是否具有选定的值。或者更好的是,使用一个通用函数:

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

在这种情况下,label1只有在设置了机器人 ComboBox 值后才会填充。或者,您也可以先将每个 ComboBox 设置为具有默认值。取决于你的要求是什么。


其他几点注意事项:

  • 你的for loop好像没用。你只是做了两次完全相同的事情!
  • 最好创建一次数组,而不是在每个事件上。创建一个类级别的变量来保存数组(这实际上在 Sayse 的回答中得到了证明)
于 2013-07-23T12:57:13.320 回答
3

这部分是一个离题的答案,但请考虑以下内容..

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

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

于 2013-07-23T13:02:04.300 回答
2

当 a 中没有选择任何内容时ComboBox,它SelectedIndex可能会变为 -1。我建议你先检查是否SelectedIndex不是-1,或者将其标准化,如果是-1,则将其视为0。

于 2013-07-23T12:57:44.200 回答