-2

Why my loop can not end? Why does it throw an exception instead?

int i=0;

ArrayList item = new ArrayList();
ArrayList list = new ArrayList();

while (reader.Read())
{
    item.Add(reader["element"].ToString());//keep data from my SQL
}

string chk2 = textBox1.Text.ToString();

for ( i = 0; i <= item.Count;i++ )
{
    if ((item[i].ToString()).Contains(chk2) )//this line got error.
    {
        list.Add(item[i]);
        MessageBox.Show(item[i].ToString());
    }
    else
    {
        MessageBox.Show("Not Found");
    }
}

Error note: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.

How i fix it please?

David Arno
  • 42,717
  • 16
  • 86
  • 131
Jet Mutt
  • 1
  • 1
  • 4
    "My code is correct." That statement is *never* a good starting point. *Always* start by assuming that when something doesn't work, your code is broken - as indeed it is here. – Jon Skeet May 23 '15 at 16:29
  • sorry i'm not good in English. – Jet Mutt May 23 '15 at 16:52
  • possible duplicate of [What is an "index out of range" exception, and how do I fix it?](http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå May 23 '15 at 17:12

1 Answers1

4

Change

for ( i = 0; i <= item.Count;i++ )

To

for ( i = 0; i < item.Count;i++ )

With 0-based index last index is less then value returned by item.Count
In your case last loop will try to find item with index, which doesn't exist in the array

Changing <= item.Count to < item.Count will prevent value of i to be more then last possible index

Fabio
  • 31,528
  • 4
  • 33
  • 72