有一个数据表(源),并且创建了此数据表的副本(复制),在此副本中,在DataGridView中修改了一些行。
修改结束后,A方法正在使用复制数据表中的修改行更新源数据表。
DataTable source ;// it is population by database.
及其副本
DataTable copy = source.Copy(); // Here is the copy datatble.
方法如下:
public static void UpdateData(DataTable source, DataTable copy)
{
foreach (DataRow row in copy.Rows)
{
if (row.RowState == DataRowState.Modified)
{
var relRow = source.Select("Id = '" + row["Id"] + "'");
if (relRow.Any())
{
//relRow[0] = row; //This statement is not udating row in the source dataTable.
foreach (var column in copy.Columns)
{
relRow[0][column.ColumnName] = row[column.ColumnName];
}
}
}
else if (row.RowState == DataRowState.Added)
{
//Performing some operations to for checking additional values. modiging 'row' with some relative data, and adding to source.
source.Rows.Add(row.ItemArray);
}
}
return source;
}
将行对象分配给datarows数组的第一个元素(如relRow[0] = row
)时,它不会更新源数据表,但它在relRow [0]中的debuggin中显示已修改的数据。
逐列分配,反映数据表中的更改。
所以,问题是:为什么relRow[0] = row
没有在源数据表中更新?
感谢。
答案 0 :(得分:1)
通过编写relRow[0] = row;
,您只需重新分配relRow的引用,修改本地数组的第0个元素。它实际上并没有改变表中行的内容。您的代码与:
DataRow[] localRows;
// here, localRows will reference items in the source table.
// Below, you overwrite the reference.
localRows = source.Select("Id = '" + row["Id"] + "'");
if(localRows.Any())
{
//changes what reference the 0th element of the localRows array points to,
// doesn't change anything about the datatable.
// localRows[0] now points to the local variable row (i.e. the item from copy)
localRows[0] = row;
}
要修改表格,您可以将relRow[0] = row;
替换为修改relRow的元素而不是其引用的内容:
for(var col = 0; col < source.Columns.Count; i++)
{
relRow[0][col] = row[col];
}