Vb.net – Delete last row in datagridview

vb.net

I’m trying to delete the last row of a datagridview programmatically, but I’m unable. Here’s what I’ve tried so far:

DataGridView1.Rows.RemoveAt(DataGridView1.Rows.Count - 1)

I’ve also tried to select last row and then delete it, but that hasn’t worked either

Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = True

DataGridView1.Rows.Remove(DataGridView1.CurrentRow)

Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = True

For Each row As DataGridViewRow In DataGridView1.SelectedRows
DataGridView1.Rows.Remove(row)
Next

I keep getting an error that says “Uncommitted new row cannot be deleted.”
Thanks

Best Answer

try to set your datagridview with this behavior properties
AllowUserToAddRows set it to False
then use this code

DataGridView1.Rows.RemoveAt(DataGridView1.Rows.Count - 1)
Related Topic