How to remove checked rows in datagridview

topsykretts

Well-known member
Joined
Dec 22, 2011
Messages
47
Programming Experience
Beginner
Hello, I will be grateful if someone help me with this problem. I have an unbounded datagridview, which has a two columns named "iName" and "Checked". Column "Checked" allows checking by checkbox. I want to remove all checked rows by single click on the button.

I tried using code below. Am I doing something wrong?
VB.NET:
      For i = 0 To DataGridView1.Rows.Count - 1
            If DataGridView1.Rows(i).Cells("Checked").Value Then
                DataGridView1.Rows.RemoveAt(i)
            End If
        Next
 
If you have that code and you're asking us whether you're doing something wrong then presumably it's not doing as expected, so you should be explaining to us exactly what you expect and exactly what happens. If there's an exception thrown then there's an error message so you should be providing that and any other diagnostic information to us.

That said, there's an obvious issue in that code to anyone with some experience. Let's say that you have 10 rows in your grid, at indexes 0 to 9. Let's say that the first four rows are unchecked so the loop continu4es doing nothing until i equals 4. At that point, the If condition evaluates to True so the row at index 4 is removed. That means that the index of every subsequent row is reduced by 1, so the row that was at index 5 is now at index 4 and the last row, which was at index 9 is now at index 8. Your loop continues and i becomes 5, so you next text the row at index 5. That means that you just skipped the row that is now at index 4. Worse than that, the limit for the loop counter has already been set to 9 when the loop started but there is no longer a row at index 9, so the If line will throw an IndexOutOfRangeException.

If you want to remove items from a collection in a loop like that then you must loop backwards, from the highest index to the lowest. That way, removing an item will only affect the indexes of the items that you've already visited and not the ones that you are yet to visit.

On a different note, you obviously have Option Strict Off or that code would not compile. I suggest that you turn Option Strict On and leave it On for this and all future projects. You'll have to fix some errors that it detects but doing so will force you to write more robust code. In this particular case, you are treating `DataGridView1.Rows(i).Cells("Checked").Value` as though it is type Boolean. It may be true that the data itself is type Boolean but that Value property is type Object. Such implicit narrowing conversions are not allowed with Option Strict On. You must always make your narrowing casts and conversions explicit so that the type of data expected is the type of data provided. In this case, a Boolean is expected so provide a Boolean:
If CBool(DataGridView1.Rows(i).Cells("Checked").Value) Then
 
Back
Top