user3080392
user3080392

Reputation: 1224

Delete last row in datagridview

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

Upvotes: 1

Views: 13304

Answers (4)

Ragesh Valeroso
Ragesh Valeroso

Reputation: 41

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)

Upvotes: 4

Tarak Bhavsar
Tarak Bhavsar

Reputation: 145

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.

Upvotes: 0

user3080392
user3080392

Reputation: 1224

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

Upvotes: 0

Victor Zakharov
Victor Zakharov

Reputation: 26414

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

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

Upvotes: 1

Related Questions