KB Article A1468
Visible to All Users

How to resolve the ArgumentOutOfRangeException when deleting an item from the grid's data list

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?

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.