Problem with DataGridView

J

John Wright

I have a datagridview control on my form that is not databound. The first
column is a checkbox that I want to check the value and if checked remove the
row from the grid. When I do this, however, I can only remove half of the
checked rows. So if my grid has all the items checked (4 items for example)
only two of them are removed leaving two. The next click, removes one row
leaving one, then the thrid click removes the last row. I am attaching the
code I have tried (I have tried both of these ways with the same result).
Can anyone see what I am doing wrong? I am sure it is obviouse, but I am
tired of looking at this code and need another set of eyes.

For Each dr As DataGridViewRow In dgEPNItems.Rows
If dr.Cells(0).Value = True Then
dgEPNItems.Rows.Remove(dr)
'update the qty
If IsNumeric(txtQuantity.Text) Then
txtQuantity.Text -= 1
End If
End If
Next

'I tried this way as well with the same result
For i = 0 To dgEPNItems.Rows.Count - 1
Dim dr As DataGridViewRow
dr = dgEPNItems.Rows(i)
If dr.Cells(0).Value = True Then
dgEPNItems.Rows.Remove(dr)
End If
Next
John
 
B

Branco Medeiros

John said:
I have a datagridview control on my form that is not databound.  The first
column is a checkbox that I want to check the value and if checked removethe
row from the grid.  When I do this, however, I can only remove half of the
checked rows.  
'I tried this way as well with the same result
            For i = 0 To dgEPNItems.Rows.Count - 1
                Dim dr As DataGridViewRow
                dr = dgEPNItems.Rows(i)
                If dr.Cells(0).Value = True Then
                    dgEPNItems.Rows.Remove(dr)
                End If
            Next

When you delete row i, row i+1 takes its place, and row i+2 becomes
the next row in turn. Therefore when you hit Next you're constantly
skipping a row whenever you delete the current one.

If you loop from Rows.Count -1 to 0 you won't skip then (otherwise
you'd have to use a Do...Loop, not a For...Next one). Another approach
would be to save the marked rows to a separate list and then loop
*that* list deleting each row.

HTH.

regards,

Branco.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top