2016-01-19 104 views
0

在我的WinForms應用程序中,我填充了兩個如下所示的DataGridView;DataTable.ImportRow無法正常工作

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); 

但問題是一樣的。

回答

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的恐懼情緒說出了適合這種情況的短語。 「我的壞」