【发布时间】: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 部分、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);
但问题是一样的。
【问题讨论】:
标签: c# winforms datagridview datatable