【问题标题】:Return only the changed rows of a datagridview?仅返回数据网格视图的更改行?
【发布时间】:2014-07-31 13:56:03
【问题描述】:

我有一个包含 datagridview 的 winform。表格与数据完全脱节。代码隐藏调用一个 web 服务,它返回一个表。该表成为 datagridview 的数据源。一旦显示了 datagridview,用户就可以编辑他们想要的任何行。目前,当他们点击“更新”按钮时,网格中的每一行都会返回。

有没有办法只返回 datagridview 中更改的行?

更新:根据 Tezzo 在下面的回答,我能够做到这一点:

var changedRows = ((DataTable)dataGridView1.DataSource).GetChanges(DataRowState.Modified).Rows;

【问题讨论】:

  • 你能告诉我们更新代码吗?你在哪里退货(以及如何)?
  • 从哪里返回?事件?如果提供一些代码会更有帮助。您可以复制从 web 服务返回的表,然后在用户完成编辑后,将每一行分别与原始表中的行进行比较,然后输出不匹配的行。或者跟踪 CellValueChanged 事件更改了哪些行。根据提供的信息,有 2^30 种方法可以做到这一点

标签: c# winforms datagridview


【解决方案1】:

您可以使用GetChangesDataTableretrieve changes

因此您可以将此代码与DataGridView 一起使用:

CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows

【讨论】:

【解决方案2】:

我在 C# 中提出了一个可行的解决方案,其中我说明用户编辑当前单元格然后执行保存/更新而不移出已编辑的行。对GetChanges() 的调用将无法识别当前编辑的行,因为它的RowState 仍被标记为“Unchanged”。我还会调用移动到下一行,以防用户停留在当前正在编辑的单元格上,因为 GetChange() 不会触及最后编辑的单元格。

//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();
}

【讨论】:

    【解决方案3】:

    这是一种使用 C# 获取已在 DataGridView 中修改的所有行的简单方法:

     DataRowCollection modifiedRows = ((DataTable)YourGridView.DataSource).GetChanges(DataRowState.Modified).Rows;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多