7938

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

Question:

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?

Answer1:

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)?

Answer2:

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

Answer3:

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

Recommend

  • Weighted round robin dns between 2 Cloudfront distributions
  • Python Paramiko send CTRL+C to an ssh shell
  • Entity Framework unable to delete database, database in use
  • Is is safe to use HSQLDB for production? (JBoss AS5.1)
  • Is there a way to disable a specific event in kendo ui scheduler?
  • Vuejs: Lifecycle hooks of child routerview components using keep alive
  • Using Sax parsing to edit and write XML in VB6
  • Retrieve list of sent friend requests from friend_request FQL table
  • CakePHP 2.0.4 - findBy magic methods with conditions
  • Problem deserializing objects from cache on MyBatis 3/Java
  • d3 v4 drag and drop with TypeScript
  • Word Open XML Mail Merge
  • How do I alternate colors in Flat List (React Native)
  • Meteor: Do Something On Email Verification Confirmation
  • why do I get the error when installing the gem 'pg'? [duplicate]
  • Django: Count of Group Elements
  • SignalR .NET Client Invoke throws an exception
  • Using variable in a value field in jMeter
  • Using $this when not in object context
  • Retrieving value from sql ExecuteScalar()
  • Array.prototype.includes - not transformed with babel
  • Volley JsonObjectRequest send headers in GET Request
  • Accessing IRQ description array within a module and displaying action names
  • Sending data from AppleScript to FileMaker records
  • MySQL WHERE-condition in procedure ignored
  • vba code to select only visible cells in specific column except heading
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Build own AppleScript numerical error handling
  • Websockets service method fails during R startup
  • Do I've to free mysql result after storing it?
  • Google cloud sdk not working when python points python3
  • Is there a mandatory requirement to switch app.yaml?
  • Transpose CSV data with awk (pivot transformation)
  • Hits per day in Google Big Query
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal