IndexOutOfRangeException with BindingContext

  • Thread starter Thread starter Stephen.Haeney
  • Start date Start date
S

Stephen.Haeney

I have a datagrid bound to a strongly typed custom collection. I have
a Delete button on my form that calls the following code:

if ( this.BindingContext[myDataSource].Count > 0 )
{
myDataSource.RemoveAt( this.BindingContext[myDataSource].Position
);
}

I was expecting the button press to remove the elevant row from the
Datagrid, but I get an IndexOutOfRangeException saying No value at
index 2.
If I add the following below the RemoveAt call, everything works
correctly

this.dataGrid1.DataSource = null;
this.dataGrid1.DataSource = myDataSource;

I should not have to rebind my datagrid to my datasource. Can anyone
tell me what I have done wrong?
 
Stephen,

Does your custom collection implement the IBindingList interface? I
assume it doesn't. When it implements this interface, it implements a
ListChanged event which indicates to whatever is binding to your collection
that the collection itself has changed. If you didn't implement this, then
you would have to always rebind to your collection, because the grid has no
clue when the list has changed (it only knows what it read from the list on
hookup).

Hope this helps.


Stephen.Haeney said:
I have a datagrid bound to a strongly typed custom collection. I have
a Delete button on my form that calls the following code:

if ( this.BindingContext[myDataSource].Count > 0 )
{
myDataSource.RemoveAt( this.BindingContext[myDataSource].Position
);
}

I was expecting the button press to remove the elevant row from the
Datagrid, but I get an IndexOutOfRangeException saying No value at
index 2.
If I add the following below the RemoveAt call, everything works
correctly

this.dataGrid1.DataSource = null;
this.dataGrid1.DataSource = myDataSource;

I should not have to rebind my datagrid to my datasource. Can anyone
tell me what I have done wrong?
 
Back
Top