超出范围的例外 [英] out of range exception

查看:76
本文介绍了超出范围的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里得到超出范围的错误

 私有  Sub  Button4_Click( ByVal  sender  As  System。对象 ByVal  e 作为 System.EventArgs)句柄 Button4.Click 
Dim i As 整数
i = 0
对于 i = 0 DataGridView1.RowCount - 1
如果 DataGridView1.Rows(i).Cells( 0 )。Value.ToString()= 然后 ' 此处错误
DataGridView1.Rows.RemoveAt(i)
结束 如果
下一步



any救命?奇怪的错误我把-1

解决方案

嗯。

想想它片刻。

比方说,你的数据网格视图中有3个项目。

所以你将循环3次,我设置为0,1和2.

但是......在索引0处理完项目后,将其删除。因此,下一次,您将处理索引1处的项目,该项目曾经是索引2,然后将其删除。你接下来要处理什么项目?



要么通过索引而不是向上,要么在循环后使用Clear删除所有项目。

试试这个



 如果 DataGridView1 .Rows(i).Cells( 0 )。值+   =   然后 
DataGridView1.Rows.RemoveAt(i)


如果删除行,则 RowCount 会改变,你会得到一个超出范围的例外。



你应该首先在循环中收集你想要删除的内容然后删除它们。

  Dim  toremove  As  列表(  整数

对于 i = 0 DataGridView1.RowCount - 1
< span class =code-keyword> If DataGridView1.Rows(i).Cells( 0 )。Value.ToString()= 然后
toremove.Add(i )
结束 如果
下一步

对于 每个 i as 整数 toremove
DataGridView1.Rows.RemoveAt(i )


I get an out of range error here

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Dim i As New Integer
        i = 0
        For i = 0 To DataGridView1.RowCount - 1
         If DataGridView1.Rows(i).Cells(0).Value.ToString() = "" Then 'here error
         DataGridView1.Rows.RemoveAt(i)
            End If
        Next


any help? strange error I have put the -1

解决方案

Um.
Think about it go a moment.
You have, say, 3 items on your data grid view.
So you will go round the loop 3 times, with i set to 0, 1, and 2.
But... After you have processed the item at index 0, you remove it. So the next time round, you process the item at index 1, which used to be at index 2, then delete it. What item are you going to process next?

Either go down through the indexes instead of up, or use Clear after the loop to remove all the items.


Try this

If DataGridView1.Rows(i).Cells(0).Value + "" = "" Then 
DataGridView1.Rows.RemoveAt(i) 


If you remove rows then the RowCount will change and you will get an out of range exception.

You should gather what you want to remove first in a loop then remove them afterwards.

Dim toremove As New List(Of Integer)

For i = 0 To DataGridView1.RowCount - 1
  If DataGridView1.Rows(i).Cells(0).Value.ToString() = "" Then
     toremove.Add(i)
  End If
Next

For each i as Integer in toremove
  DataGridView1.Rows.RemoveAt(i)


这篇关于超出范围的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆