Index was out of range. Must be non-negative and less than the size of the collection

╄→гoц情女王★ 提交于 2019-12-23 20:12:35

问题


Error is: Index was out of range. Must be non-negative and less than the size of the collection.

Scenario: I have a desktop application which loads XML Files and display the data in Grid. Now, I want to insert another file and want to append the data in both files. But, when I try to merge the data (I mean add the rows to DataTable which has rows of perviously opened file)...I am getting this error.

if (strPreviousFile != "")   
{  
  dgvBooksDetails.DataSource = dtBooks;   
  int intCurrentRows = dgvBooksDetails.Rows.Count;   
  intBooksCounter = intBooksCounter + intCurrentRows;   
  for (int c = intCurrentRows; c < intBooksCounter; c++)  
  {   
    Book objBook = new Book();   
    objBook.ID = BookID[c];   
    objBook.Title = BookTitle[c];  
    objBook.Author = BookAuthor[c];  
    objBook.Genre = BookGenre[c];  
    objBook.Price = Double.Parse(BookPrice[c]);  
    objBook.PublishDate = DateTime.Parse(BookPublish_Date[c]);  
    objBook.Description = BookDescription[c];  
    dtBooks.Rows.Add(objBook.ID, objBook.Title, objBook.Author, objBook.Genre,
                     objBook.Price, objBook.PublishDate, objBook.Description);   
  }
}

How can I overcome this error?


回答1:


The line causing trouble is this:

int intCurrentRows = dgvBooksDetails.Rows.Count;

You take this value as start for your loop. However, the rows collection counts from 0 to Count-1, so using Count to access a value of the rows collection causes an index out of bounds error.

Another thing: BookTitle, BookAuthor etc. are also indexed from 0 to Count-1 (or Length-1 if they are arrays). I'm not sure from what you've told us, but are you sure that these collections can be accessed by index the way you do? I mean, could it be they only contains the items to be added and thus need to be indexed from 0 to X instead of number of existing items to number of existing items + number of new items (that's what you do in your code)?




回答2:


Well it seems you have an array n long and you are trying to access the nth or greater element within it. Indexes are 0 based and so an n sized array must be accessed by indexes 0 to n-1.




回答3:


Make sure that your arrays (BookTitle, BookAuthor, BookGenre, BookPrice, BookPublish_Date, and BookDescription) have the correct length (minimum intBooksCounter).



来源:https://stackoverflow.com/questions/11502745/index-was-out-of-range-must-be-non-negative-and-less-than-the-size-of-the-colle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!