How do I resolve index was out of range. Must be non-negative and less than the size of the collection. Error How do I resolve index was out of range. Must be non-negative and less than the size of the collection. Error database database

How do I resolve index was out of range. Must be non-negative and less than the size of the collection. Error


To find out, you need to look at the data in your app while it is running - and we can;t do that!So, its going to be up to you.Put a breakpoint on the first line in the method, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

The most likely cause is that the number of rows returned from your query is not the same as the number of elements in your array.

int i = 0;foreach (DataRow row in dtReportTbl.Rows){    ... = salGradelist[i]; // <-- Exception here    ...    i++;}

If the query returns fewer rows than the number of elements in your array, then your code will just ignore the later elements.

But if it returns more rows, then the variable i is going to go beyond the end of your array, and you'll get the "index out of bounds" exception.

You'll need to debug your code and your query to find out why the number of rows returned doesn't match the number of elements in your array.