DataGridView row delete

SeanPress 206 Reputation points
2023-12-30T19:44:59.29+00:00

Hi,

I have created a Windows Form app in Visual Basic with a DataGridView to allow the user to enter rows of information in table form. I added a delete row button and use the below code to delete rows from the data grid view. It works perfectly, except if I accidentally press the delete button when the blank row automatically added to the bottom of the DataGridView. I get a system NullReference exception as per the snapshot below.

Does anyone have better code for the button or a code to bring up a message box telling the user not to delete the bottom row then return to the app.

Dim rowIndex As Integer = DataGridView1.CurrentCell.RowIndex
If rowIndex >= 0 AndAlso rowIndex < DataGridView1.Rows.Count - 1 Then
      DataGridView1.Rows.RemoveAt(rowIndex)
End If

image

Developer technologies VB
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2024-01-01T06:40:54.7533333+00:00

    @SeanPress, Welcome to Microsoft Q&A, based on your description, you want to handle the NullReference exception when you remove the bottom row.

    I recommend that you could check if the DataGridviewCell is nothing first.

    Here is a code example you could refer to.

     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
         Dim currentcell As DataGridViewCell = DataGridView1.CurrentCell
         If currentcell IsNot Nothing Then
             Dim rowIndex As Integer = DataGridView1.CurrentCell.RowIndex
             If rowIndex >= 0 AndAlso rowIndex < DataGridView1.Rows.Count - 1 Then
                 DataGridView1.Rows.RemoveAt(rowIndex)
             End If
         Else
             MessageBox.Show("please don't remove the bottom row")
         End If
     End Sub
    
    
    

    Then, when you remove the bottom row, you will get the message box to tell you that please don't remove the bottom row.

    Tested result:

    User's image

    Hope it could help you.


    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 additional answers

Sort by: Most helpful

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.