Monday, November 28, 2011

Enumerators in datagridviews - careful

Wrote some code that was doing some copying of rows in datagridviews based on what the user had selected.
I should have seen this one coming, but the selected rows changes out from under you if you write code like this:

For each SelectedRow as DataGridViewRow in dgvSource.SelectedRows
  dgvSource.Rows.Add(NewRowBasedOnSelectedRow)
Next

As soon as you add the row, the selected rows property gets reset.
I actually trapped the selection changing. It goes from what is was, to 0, to 1.

The workaround was simple - build a second list of rows to process before I start adding to the source
The annoying this is if you do this kind of thing with a list, you get an exception thrown because the enumerator fails. The datagridview must be trapping the exception.


No comments:

Post a Comment