Error message: index -1 does not have a value in datagridview
scenario: The grid was bound to a simple object collection. The object contained
string and decimal properties, nothing to fancy. When an item was added to
the collection I would databind as follows (this happened on each item
"Add"):
If I added an item after I deleted all the items in
the grid (collection) and try to select it the grid would bomb out with the
following error: "Index -1 does not have a value".
myObject.CollectionProperty.Add(myBasicObject);
dgvGrid.DataSource = myObject.CollectionProperty;
This will cause the above error
solution:
set the simple object collection in to a binding source and set the resetbinding to false like below
Againg assign the binding source to the grid
bsBindingSource.ResetBindings(false);
bsBindingSource.DataSource = myObject.CollectionProperty;
dgvGrid.DataSource = bsBindingSource;
to the Add routine, just after the object is added to the collection.
Viola! Problem was fixed, and I no longer needed to bind the grid twice. I
was able to make the binding work now with just this:
scenario: The grid was bound to a simple object collection. The object contained
string and decimal properties, nothing to fancy. When an item was added to
the collection I would databind as follows (this happened on each item
"Add"):
If I added an item after I deleted all the items in
the grid (collection) and try to select it the grid would bomb out with the
following error: "Index -1 does not have a value".
myObject.CollectionProperty.Add(myBasicObject);
dgvGrid.DataSource = myObject.CollectionProperty;
This will cause the above error
solution:
set the simple object collection in to a binding source and set the resetbinding to false like below
Againg assign the binding source to the grid
bsBindingSource.ResetBindings(false);
bsBindingSource.DataSource = myObject.CollectionProperty;
dgvGrid.DataSource = bsBindingSource;
to the Add routine, just after the object is added to the collection.
Viola! Problem was fixed, and I no longer needed to bind the grid twice. I
was able to make the binding work now with just this:
1 comments:
works like a charm - Thank you!!!
the error wasn't explicit as refering to the datagrid, but after some time spent, it only made sense to have the problem there.
Post a Comment