1
votes

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

4
Have you tried deleting the record from the underlying datasource (e.g. bindingsource) and refreshing the grid?majjam

4 Answers

4
votes

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)
1
votes

Chances are you need to call RejectChanges on your row in the DataSource.

For new rows, it means deletion. Also see this:

0
votes

Instead of deleting the last row, I ended up just bypassing it. I figured out how to select all of the rows except for the last one, and then I implemented code that referred to just the selected rows.

Me.DataGridView1.ClearSelection()

Me.DataGridView1.SelectAll()
Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = False

0
votes

Except deleting the last uncommitted row you can prevent user to select it. By inserting below code to cellclick event of your datagridview.

 Dim i As Integer = DataGridView1.CurrentRow.Index

    If DataGridView1.Item(0, i).Value.ToString() = "" Then
        MsgBox("Sorry...Blank Row")
        DataGridView1.ClearSelection()
        DataGridView1.Rows(i - 1).Selected = True
        i = i - 1
    End If

Your other code goes here.