getting the rowindex of a deleted row in datagridview in vb.net

5.5k views Asked by At

following is the issue.

I want to get the row index and column index of the deleted row of datagridview for some calculations and updations.but the error i keep getting is object reference not set to an instance of an object. i have written the code in the rows removed event of the data gridview.heres the code.

Try


    delflag = True
    Dim quant As Integer
    If dgsalesitem.CurrentRow.Cells(0).Value = 0 Then
        quant = dgsalesitem.CurrentRow.Cells(1).Value
    Else
        quant = dgsalesitem.CurrentRow.Cells(0).Value
    End If
    UpdateStock(dgsalesitem.CurrentRow.Cells(2).Value.ToString, dgsalesitem.CurrentRow.Cells(9).Value.ToString, dgsalesitem.CurrentRow.Cells(10).Value.ToString, quant, False)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
2

There are 2 answers

2
Edper On BEST ANSWER

You could catch the UserDeletingRow event when user is about to delete the row:

Private Sub dgsalesitem_UserDeletingRow(sender As Object, e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles dgsalesitem.UserDeletingRow    
 Try
   delflag = True
   Dim quant As Integer
   If e.Row.Cells(0).Value = 0 Then
      quant = e.Row.Cells(1).Value
   Else
      quant = e.Row.Cells(0).Value
   End If
   UpdateStock(e.Row.Cells(2).Value.ToString, e.Row.Cells(9).Value.ToString, e.Row.Cells(10).Value.ToString, quant, False)
 Catch ex As Exception
    MsgBox(ex.Message)
 End Try
End Sub

And if you want to get the Row Index of the row deleted, you could simply use:

 e.Row.Index
0
OSKM On

under .RowsRemoved use e.RowIndex to get the index of the row removed.