Update database with changes made to DataTable... confusion
Asked Answered
P

2

12

If I fill a DataTable with DataAdapter.Fill(DataTable); and then make changes to a row in the DataTable with something simple like this: DataTable.Rows[0]["Name"] = "New Name"; how can I easily save those changes back to the database? I assumed I could call DataAdapter.Update(DataTable); but I read that only works with a TableAdapter(?).

Provo answered 7/3, 2013 at 13:56 Comment(0)
P
35

Here is an actual helpful answer in case anyone else needs to know how to do this:

string selectStatement = "SELECT * FROM Contact";
System.Data.DataTable dt = new System.Data.DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = new SqlCommand(selectStatement, conn);
SqlCommandBuilder cb = new SqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Name"] = "Some new data here";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
Provo answered 8/3, 2013 at 12:26 Comment(1)
@blackholeearth0_gmail it seems like it returns an UPDATE command reflecting the changes made to the row when assigning dt.Rows[0]["Name"] = "Some new data here" valueFilippo
A
-1

Take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.

using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
      foreach (DataColumn col in table.Columns)
      {
          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
      }
      bulkCopy.BulkCopyTimeout = 600;
      bulkCopy.DestinationTableName = destinationTableName;
      bulkCopy.WriteToServer(table);
}
Activator answered 5/5, 2015 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.