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 の 1 つに選択された値がないため、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は役に立たないようです。まったく同じことを 2 回行っているだけです。
  • イベントごとに作成するよりも、配列を 1 回作成することをお勧めします。配列を保持するクラス レベルの変数を作成します (これは、Sayse の回答で実際に示されています)。
于 2013-07-23T12:57:13.320 に答える
2

で何も選択されていない場合はComboBoxSelectedIndex-1 になることがあります。SelectedIndex最初に-1でないかどうかを最初に確認するか、-1の場合は0として扱うように正規化することをお勧めします。

于 2013-07-23T12:57:44.200 に答える