在我的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
部分,DataView
和DataRowCollection.Find
方法,以纳入一些过滤功能。如果没有这些,代码就会按预期工作。
另一个编辑:我从PrimaryKey
方法中移除了PopulateData
部分并修改了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);
但问题是一样的。
答案 0 :(得分:2)
好的,那是因为我的代码执行顺序。让我解释一下。
这是我为交换执行的代码;
//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow);
此行首先已删除,然后才会导入dtSelected
表。这就是dtSelected
永远不会按照我尝试的方式导入行的原因。
因此,更改代码的顺序可以解决我的问题;
//Exchange row between grids
dtSelected.ImportRow(selectedRow);
dtAll.Rows.RemoveAt(foundRow);