Vincent Prince Assah Vincent Prince Assah - 3 months ago 87
Vb.net Question

Remove Current/last Row From Datagridviewrows in vb.net

I am trying to remove the current row from datagridview which is not bound to any datasource and AllowUserToAddRows property is False.

I add rows to datagridview using the code

Purchases.Rows.Add(selectedrow.Cells(0).Value, selectedrow.Cells(1).Value, selectedrow.Cells(2).Value, selectedrow.Cells(6).Value, "", "", selectedrow.Cells(3).Value


And i use this code to remove current row

Private Sub Purchases_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Purchases.CellEndEdit
Try
If CDbl(Purchases.CurrentRow.Cells("Column7").Value) - CDbl(Purchases.CurrentRow.Cells(4).Value) < 0 Then
MessageBox.Show("Quantity entered is more than total in Stock " & vbNewLine & vbNewLine & Purchases.CurrentRow.Cells(1).Value & " Has " & stock & " in Stock" & vbNewLine & vbNewLine & "Increase Stock Level or Reduce Quantity Entered or See System Administrator for Help", "Pharm App " & Today.Year & "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Purchases.Rows.Remove(Purchases.CurrentRow)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub


but i get an error saying

"Operation is not valid because it results in a reentrant call to SetCurrentCellAddressCore function"

I tried to remove the last row with

Purchases.Rows.RemoveAt(Purchases.RowCount - 1)


and i get the same error.

Please help as i am a newbie.

Answer

You would have to remove the row after the CellEndEdit event, so replace this line:

Purchases.Rows.Remove(Purchases.CurrentRow)

with this:

Me.BeginInvoke(New Action(Sub() Purchases.Rows.Remove(Purchases.CurrentRow)))
Comments