【问题标题】:DataTable.ImportRow not workingDataTable.ImportRow 不工作
【发布时间】:2016-01-19 05:37:58
【问题描述】:

在我的WinForms 应用程序中,我正在填充两个DataGridView,如下所示;

private void PopulateData()
{
    //Load data
    DataTable dtAll = LoadData();
    DataTable dtSelected = dtAll.Clone();

    dtAll.PrimaryKey = new DataColumn[] { dtAll.Columns["PK"] };
    dtSelected.PrimaryKey = new DataColumn[] { dtSelected.Columns["PK"] };

    DataView leftGridView = new DataView(dtAll);
    DataView rightGridView = new DataView(dtSelected);

    dgvLeft.AutoGenerateColumns = false;
    dgvLeft.DataSource = leftGridView;

    dgvRight.AutoGenerateColumns = false;
    dgvRight.DataSource = rightGridView;
}

然后在其他地方,我在两个DataGridView 之间交换列,如下所示;

private void ExchangeData()
{
    //Get current row of left grid
    DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;

    //Find the row from all data table
    DataRow foundRow = dtAll.Rows.Find(selectedRow["PK"].ToString());

    if (foundRow == null)
        return;

    //Exchange row between grids
    dtAll.Rows.Remove(foundRow);
    dtSelected.ImportRow(foundRow); 
}

但只有dtAll.Rows.Remove(foundRow); 正确完成并反映在DataGridView 中,但dtSelected.ImportRow(foundRow); 行不会将行添加到dtSelected。我将此行更改为dtSelected.ImportRow(selectedRow);,但结果相同。有什么想法吗?

MSDN 中引起我注意的是;

如果新行违反约束,则不会将其添加到数据中 表。

注意:此问题与以下 SO 帖子无关;
DataTable.ImportRow is not adding rows
Why DataTable.Rows.ImportRow doesn't work when passing new created DataRow?
DataTable importRow() into empty table
ImportRow is not working

编辑:我稍后添加了PrimaryKey 部分、DataViewDataRowCollection.Find 方法以合并一些过滤功能。如果没有这些,代码将按预期工作。

另一个编辑:我从PopulateData 方法中删除了PrimaryKey 部分并修改了ExchangeData 方法如下;

//Get current row of left grid
DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;

//Find the row from all data table
int foundRow = dtAll.Rows.IndexOf(selectedRow);

//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow); 

但问题是一样的。

【问题讨论】:

    标签: c# winforms datagridview datatable


    【解决方案1】:

    好的,那是因为我的代码执行顺序。让我解释一下。

    这是我为交换执行的代码;

    //Exchange row between grids
    dtAll.Rows.RemoveAt(foundRow);
    dtSelected.ImportRow(selectedRow); 
    

    这里的行在被导入dtSelected 表之前首先被删除。这就是为什么dtSelected 无论如何我都没有导入行。

    所以更改代码的顺序可以解决我的问题;

    //Exchange row between grids
    dtSelected.ImportRow(selectedRow);
    dtAll.Rows.RemoveAt(foundRow);
    

    Inside Out 中的恐惧情绪说出了适合这种情况的短语。 “我的坏”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 2018-12-22
      • 2016-04-19
      相关资源
      最近更新 更多