Search code examples
c#exceldatagridviewindexoutofrangeexception

"Out Of Range Exception" Error when trying to load DataGridView Row Values into Comboboxes


I'm trying to write a program that loads an excel sheet into a Datagridview (successfully), but when I select a Row to try and load them into my Comboboxes I get this Error Message ("System.ArgumentOutOfRangeException: "Index was out of range. Must be non-negative and less than the size of the collection. Arg_ParamName_Name").

If I delete the If Statement the same Error appears on the first "Items.Add" Line of Code.

enter image description here


Solution

  • Array indices start at zero in C#. This means that

    array[array.Length]
    

    is out of range while

    array[array.Length - 1]
    

    is not out of range provided that 0 < array.Length.