简体   繁体   中英

Error: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

I an getting an exception "Index was out of range. Must be non-negative and less than the size of the collection" in the following code.Here in the code actually what going on is , handling some duplicate values which is finally occupying in a data grid

try
         {
            int index = alerts.Find(alertName);
            if (index >= 0 && tblAlarm.Rows.Count > idx)
            {
               DataRow row = tblAlarm.Rows[idx];
               m_dcDuplicates.ReadOnly = false;

            }
         }

Do i need to increase the size of types like int to long ? or any additional check in code is required ?

Since you are using a lock statement, this is presumably a multi-threaded implementation.

A likely cause is that you are failing to synchronize access to your object properly. Look at any other code that updates the collection ( this in your code above) - post it if the problem isn't obvious.

UPDATE

For example, in your updated source code, the indexer's setter is not synchronized:

public Alert this[int index]
{
    get ...
    set
    {
        this.List[index] = value;
    }
}

You probably need the following:

public Alert this[int index]
{
    get ...
    set
    {
        lock(this)
        {    
            this.List[index] = value;
        }
    }
}

Another oddity in your code is that the Add and Remove methods reference this.InnerList , while the indexer references this.List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM