Reputation: 4848
I have a winform that contains a datagridview. The form is totally disconnected from the data. The codebehind calls a webservice, which returns a table. That table becomes the datasource for the datagridview. Once the datagridview is displayed, a user can edit any row. Currently, when they hit the 'Update' button, every row in the grid is returned.
Is there a way to return only the changed rows in the datagridview?
UPDATE: Based off Tezzo's answer below, I was able to do this:
var changedRows = ((DataTable)dataGridView1.DataSource).GetChanges(DataRowState.Modified).Rows;
Upvotes: 3
Views: 13352
Reputation: 480
Here is a simple way to get all rows which have been modified in a DataGridView using C#:
DataRowCollection modifiedRows = ((DataTable)YourGridView.DataSource).GetChanges(DataRowState.Modified).Rows;
Upvotes: 0
Reputation: 11
I have come up with a working solution in C# where I account for a user editing the current cell then performing a Save/Update without moving out of the edited row. The call to GetChanges()
won't recognize the current edited row due to its RowState
still being marked as "Unchanged
". I also make a call to move to the next row in case the user stayed on the current cell being edited as GetChange()
won't touch the last edited cell.
//Move to previous cell of current edited row in case user did not move from last edited cell
dgvMyDataGridView.CurrentCell = dgvMyDataGridView.Rows[dgvMyDataGridView.CurrentCell.RowIndex].Cells[dgvMyDataGridView.CurrentCell.ColumnIndex - 1];
//Attempts to end the current edit of dgvMyDataGridView for row being edited
BindingContext[dgvMyDataGridView.DataSource, dgvMyDataGridView.DataMember.ToString()].EndCurrentEdit();
//Move to next row in case user did not move from last edited row
dgvMyDataGridView.CurrentCell = dgvMyDataGridView.Rows[dgvMyDataGridView.CurrentCell.RowIndex + 1].Cells[0];
//Get all row changes from embedded DataTable of DataGridView's DataSource
DataTable changedRows = ((DataTable)((BindingSource)dgvMyDataGridView.DataSource).DataSource).GetChanges();
foreach (DataRow row in changedRows.Rows)
{
//row["columnName"].ToString();
//row[0].ToString();
//row[1].ToString();
}
Upvotes: 1
Reputation: 11105
You can retrieve changes in a DataTable
using GetChanges
.
So you can use this code with a DataGridView
:
CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows
Upvotes: 6