Utkarsh Agrawal Utkarsh Agrawal - 3 months ago 21
Vb.net Question

Deleting Datagridview rows using LOOP

My Data Grid View Contains One Column.
Many Rows of

DataGridView
are empty I am using Loop to remove those rows.

For j = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(j).Cells(0).Value.ToString.Length = 0 Then
DataGridView1.Rows.RemoveAt(j)
End If
Next



Error : Index was out of range. Must be non-negative and less than the
size of the collection.


Thanks in Advance!

Answer

or you can just loop from the last row:

For j = DataGridView1.RowCount - 1 To 0 Step -1
    If DataGridView1.Rows(j).Cells(0).Value.ToString = "" Then
        DataGridView1.Rows.RemoveAt(j)
    End If
Next