What is the correct code for deleting a datagridview rows in vb.net?

Kennyqui 216 Reputation points
2021-12-15T14:04:24.1+00:00

This is my code.

DataGridView1.Rows.RemoveAt(index)

The problem is when I click the delete button when there is no item in datagridview its having error.

So what is the correct code that even if you click the delete button without an item in datagridview will not error?

Please help me I'm beginner.

Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2021-12-16T05:42:39.043+00:00

    Hi @Kennyqui ,
    Because there is an uncommitted new row at the end of Datafridview.
    Please use the code above to ensure that the index value is within the deleteable range.

     If index >= 0 AndAlso index < DataGridView1.Rows.Count - 1 Then  
         DataGridView1.Rows.RemoveAt(index)  
     End If  
    

    Hope the code above could be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-12-15T14:38:15.76+00:00

    The next code should work in certain circumstances:

    If index >= 0 AndAlso index < DataGridView1.Rows.Count  Then
        DataGridView1.Rows.RemoveAt(index)
    End If
    

  2. Hanish Kapoor 1 Reputation point
    2022-12-28T18:15:00.523+00:00

    lets say my Datagridview Name is DGV1

    then use below code to delete all rows

    Dim DGV1RowCount, I As Integer  
              
    DGV1RowCount = DGV1.RowCount  
      
    For I = 0 To DGV1RowCount - 1  
         DGV1.Rows.RemoveAt(0)  
    Next  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.