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

This error just greeted me while testing a log page that uses an ASP.NET GridView control for displaying tabular data. When navigating to the last page and then trying to navigate back up to a more recent page, my code was failing on a line in the RowCommand event, which seemed strange to me. Then, I realized that the pager is in the header, which is a row, itself, and any actions on the header row go through the RowCommand function and the code was failing on a call to set thisRow = gv.rows(e.CommandArgument mod gv.PageSize). When the header row calls the RowCommand function, e.CommandArgument = -1, apparently.

A couple of solutions are:

  1. Wrap the entire contents of the RowCommand function with an if-statement to check for e.CommandArgument > -1
  2. Wrap the contents of the RowCommand function with an if-statement to check for e.CommandName = “Page”

I found solution 2 on a message board. Apparently, when you’re clicking on one of the pager buttons in the header, the CommandName is set to “Page”.

This has taken about 2 hours to troubleshoot, and the solution was simple–yet another A-S-S (Always Something Simple) solution…