1

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

user3080392
  • 1,194
  • 5
  • 18
  • 35
  • 2
    Have you tried deleting the record from the underlying datasource (e.g. bindingsource) and refreshing the grid? – majjam Jan 16 '14 at 13:44

4 Answers4

4

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)
Prisoner
  • 1,839
  • 2
  • 22
  • 38
1

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

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

Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • Thanks. However,the datagridview is actually not bound to a dataSourse. The user enters data in the datagridview then pushes a save button and the the data is saved to multiple .txt files. When the user adds info to say, row 5, then a new row 6 appears. I want to delete this last row 6 because it is messing up the program with null/empty values when the user presses the save button. – user3080392 Jan 16 '14 at 14:07
  • @user3080392: Is there any reason why DataGridView is not bound? I mean, you don't have to have it bound to a database, i.e. DataTable can be created manually. It's just easier to manage like that, and you should no longer have problems you described. Also, this is important information regarding scope of this question, so please update the question to include it there. – Victor Zakharov Jan 16 '14 at 14:10
0

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

user3080392
  • 1,194
  • 5
  • 18
  • 35
0

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.

Tarak Bhavsar
  • 145
  • 2
  • 13