为什么这个循环会抛出 System.ArgumentOutOfRangeException 错误,而不是结束?
Why does this loop throw a System.ArgumentOutOfRangeException error, rather than ending?
为什么我的循环无法结束?为什么它会抛出异常?
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");
}
}
错误 note:An 'System.ArgumentOutOfRangeException' 类型的未处理异常发生在 mscorlib.dll
附加信息:索引超出范围。必须为非负数且小于集合的大小。
请问我该如何解决?
改变
for ( i = 0; i <= item.Count;i++ )
到
for ( i = 0; i < item.Count;i++ )
对于基于 0 的索引,最后一个索引小于 item.Count
返回的值
在您的情况下,最后一个循环将尝试查找具有索引的项目,该索引在数组
中不存在
将 <= item.Count
更改为 < item.Count
将防止 i
的值超过最后一个可能的索引
为什么我的循环无法结束?为什么它会抛出异常?
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");
}
}
错误 note:An 'System.ArgumentOutOfRangeException' 类型的未处理异常发生在 mscorlib.dll
附加信息:索引超出范围。必须为非负数且小于集合的大小。
请问我该如何解决?
改变
for ( i = 0; i <= item.Count;i++ )
到
for ( i = 0; i < item.Count;i++ )
对于基于 0 的索引,最后一个索引小于 item.Count
返回的值
在您的情况下,最后一个循环将尝试查找具有索引的项目,该索引在数组
将 <= item.Count
更改为 < item.Count
将防止 i
的值超过最后一个可能的索引