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?
The line causing trouble is this:
You take this value as start for your loop. However, the rows collection counts from 0 to
Count-1, so usingCountto access a value of the rows collection causes an index out of bounds error.Another thing:
BookTitle,BookAuthoretc. are also indexed from 0 toCount-1(orLength-1if 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 ofnumber of existing itemstonumber of existing items + number of new items(that’s what you do in your code)?