Assigning a datarow to at an index of datarows which are getting by a datatable select method, not updating that datatable

1.6k Views Asked by At

There is a datatable ( source ), and a copy of this datatable is created ( copy ), and in this copy, some rows are modified in DataGridView.

After modification is over, A method is updating source datatable with modified rows in copy datatable.

DataTable source ;// it is population by database.

and its copy

DataTable copy = source.Copy(); // Here is the copy datatble.

The method is like :

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;
}

when assigning a row object to datarows array's first element like relRow[0] = row, it is not updating source datatable, but it is showing modified data while debuggin in relRow[0].

Column by column assignment reflecting changes in datatable.

So, The question is : Why relRow[0] = row not updating in source datatable?

Thanks.

1

There are 1 best solutions below

0
goric On BEST ANSWER

By writing relRow[0] = row;, you're simply re-assigning the reference of relRow, modifying the 0th element of your local array. It isn't actually changing the contents of the row in the table. Your code is the same as:

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; 
}

To modify the table, you can replace relRow[0] = row; with something that modifies the elements of relRow rather than its reference:

for(var col = 0; col < source.Columns.Count; i++)
{
    relRow[0][col] = row[col];
}