Click here to Skip to main content
15,920,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get an out of range error here
VB
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
Posted
Updated 3-Jun-14 21:02pm
v3

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.
 
Share this answer
 
Try this

VB
If DataGridView1.Rows(i).Cells(0).Value + "" = "" Then 
DataGridView1.Rows.RemoveAt(i) 
 
Share this answer
 
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.
VB
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)
 
Share this answer
 
I guess the problem is due to Remove.

This is my understanding might be I am wrong. If you have two rows then count will be 2. So the first record is removed now the second is moved to first position i.e. from 1 to 0. Now "i" is 1 but there is only record in the collection and it is at index 0.

Solution: Start the loop from last row to first i.e. Rowcount -1 to 0.
 
Share this answer
 
Either Rows or Cells may not have items defined in them. Put a break point and debug. You will know for sure why this error is coming up.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900