[英]Assigning a datarow to at an index of datarows which are getting by a datatable select method, not updating that datatable
有一個數據表(source),並創建了該數據表的副本(copy),並且在此副本中,在DataGridView中修改了一些行。
修改結束后,一種方法是使用副本數據表中的已修改行來更新源數據表。
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;
}
當將行對象分配給relRow[0] = row
數組的第一個元素(如relRow[0] = row
,它不會更新源數據表,但會在relRow [0]中調試時顯示修改后的數據。
逐列分配反映了數據表中的更改。
因此,問題是:為什么relRow[0] = row
源數據表中的relRow[0] = row
未更新?
謝謝。
通過編寫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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.