在我的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
部分,DataView
和DataRowCollection.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);
但問題是一樣的。