超出范围的例外

编程入门 行业动态 更新时间:2024-10-26 00:29:42
本文介绍了超出范围的例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

私有 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 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)

更多推荐

超出范围的例外

本文发布于:2023-10-16 12:20:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!