ponting
ponting

Reputation: 105

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 ?

Upvotes: 0

Views: 4179

Answers (1)

to StackOverflow
to StackOverflow

Reputation: 124696

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.

Upvotes: 1

Related Questions