【问题标题】:Copying rows from datagridwiew to datatable将行从datagridview复制到数据表
【发布时间】:2014-10-14 12:00:51
【问题描述】:
DataTable dt = ((DataTable)dataGridView1.DataSource).Copy();

从 DataGridview 中删除行后,读取 dt 时出现错误。 "DeletedRowInaccessibleException"

如何将未删除的行复制到数据表中?

【问题讨论】:

  • 你需要保留dt的变化吗?

标签: c# datagridview datatable datarow


【解决方案1】:
DataTable gridTable = (DataTable)dataGridView1.DataSource;

//you can call AcceptChanges() if you want !

//create data table with the same schema as gridTable !
DataTable dt = gridTable.Clone();

foreach(DataRow row in gridTable.Rows)
{
    if(row.RowState == DataRowState.Deleted)
       continue;

    //import every row from the gridTable to the new DataTable.
    dt.ImportRow(row);
}

这里有一种方法。

【讨论】:

    【解决方案2】:

    您要求不复制已删除的行,然后您可以编写

    DataTable source = (DataTable)dataGridView1.DataSource;
    DataTable dt = source.Rows
                         .Cast<DataRow>()
                         .Where(x => x.RowState != DataRowState.Deleted)
                         .CopyToDataTable();
    

    此解决方案使用 IEnumerable extensions Cast 创建一系列 DataRows,并对其应用 Where condition 检查 RowState。
    然后使用 CopyToDataTable 扩展在 DataTable 中重新实现该序列

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多