Description:
My grid is bound to an ArrayList object. When the last row in the grid is focused and the corresponding item is deleted from the ArrayList, I get the ArgumentOutOfRangeException. How can I fix this? Below is the exception's output and a snippet of my code.
"An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection."
C#ArrayList myList = new ArrayList();
...
gridControl1.DataSource = myList;
...
myList.RemoveAt(myList.Count - 1);
gridView1.LayoutChanged();
Answer:
The problem is that the CurrencyManager does not update its Position.
The best solution for this issue is to create an ArrayList or CollectionBase derived class and implement the IBindingList interface in it. We advise that you review the GridIBindingList and GridIXtraRowFilter tutorial projects shipped with the XtraGrid.
.NET Framework 2.0 and higher provides a BindingList<T> class. If you use it, you don't need to implement the IBindingList interface yourself.
If you cannot use BindingList<T> and don't want to implement IBindingList, you may call the CurrencyManager.Refresh method or update the Position property.
C#// sample #1
myList.RemoveAt(myList.Count - 1);
CurrencyManager cm = BindingContext[myList] as CurrencyManager;
cm.Refresh();
// sample #2
BindingManagerBase bm = BindingContext[myList];
if(bm.Position == myList.Count - 1)
bm.Position--;
myList.RemoveAt(myList.Count - 1);
gridView1.BeginSort();
gridView1.EndSort();
See Also:
What is the best way to refresh the on-screen data if the datasource is an ArrayList?
What could be the cause of a serialization error when I save my custom collection which is bound to a grid?