Check if New Rows Added to DataGridView and if so, Get the Collection of New Rows

4.7k views Asked by At

In a VB.NET WinForms project I have a datagridview populated by a dataset. When the user clicks a button I need to check if there are any new rows in the DGV and if so, get the collection of rows for insert into the database. (I have the DGV property AllowUserToAddRows set to True, so there's a row at the bottom of the DGV.)

The closest I could come to any progress was with the following, which gave me mixed results. The code does get the values from the new row - but only if the user has clicked out of the new row. If the the focus doesn't leave the new row it's as if that row hasn't been added to whatever behind the scenes collection of new rows is built. (Clicking out of and then back into the new row works).

If EmployeesDataSet.HasChanges(DataRowState.Modified Or DataRowState.Added) Then
    Dim changesDataSet As DataSet = EmployeesDataSet.GetChanges(DataRowState.Modified Or DataRowState.Added)
    Dim changesTable As DataTable

    For Each changesTable In changesDataSet.Tables
        Console.WriteLine("TableName: " & changesTable.TableName)
        For Each row As DataRow In changesTable.Rows
            Dim column As DataColumn
            For Each column In changesTable.Columns
                Console.Write("Value: " & row(column).ToString() & ControlChars.Tab & ", ")
            Next column
            Console.WriteLine()
        Next
    Next

End If

CaseyWilkins helped me out with a similar issue here. In that case, leaving focus in a changed cell required adding this code:

If dgvEmployees.IsCurrentCellDirty Then
    dgvEmployees.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If

In light of that I tried

If dgvEmployees.IsCurrentRowDirty Then
    dgvEmployees.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If

but that didn't do it.

I can't very well include instructions "you have to click out of the new row for it to work"! :)

3

There are 3 answers

0
marky On BEST ANSWER

LarsTech was close. The EndEdit() method needed to be called on the DataGridView's BindingSource. So my solution was

EmployeesBindingSource.EndEdit()

right at the beginning of the click event for the save button.

I found the answer on this page.

1
LarsTech On

The new row is probably still in edit mode, so try:

dgvEmployees.EndEdit();
0
Percy Kumah On

Try this:

dgvEmployees.CurrentCell = Nothing

This will force the dgv to validate the new or edited row. Do this before your Update command. It should work.