Search code examples
c#dataadapterrowstate

C# - Using DataAdapter to Update SQL table from a DataTable - SQL table not updating


I select * from an Excel spreadsheet into DataTable dt. I want to take those values and update the SQL table. The SQL table exists because of a manual import to SQL from the original Excel spreadsheet, has a primary key set. The user updates the excel sheet and I need to update the SQL values. I am setting the dt.RowState to modified in an effort to invoke the update. I get no error but the SQL table does not update. Previous test show my SQL permissions and connection is good, I can modify the table.

connectionToSQL = new SqlConnection(SQLConnString);
connectionToSQL.Open();
var cmd = new SqlCommand("SELECT * FROM TAGS$",connectionToSQL);                 
var da = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da);
foreach (DataRow r in dt.Rows)
{
    r.SetModified();
}
da.Update(dt);   

Solution

  • I tried commenting but was told to re-read the question. So I did, and it didn't help :) You have very little code in that example which ties dt (you say this is populated from Excel) to the database. You have the variables connectionToSQL, cmd, da and b. These are connected to a database. You then iterate through dt, which isn't. This is why in my comment I asked for the example sourcecode where you're modifying rows in dt - because I presumed you would have that somewhere, in order to expect that the changes would jump from Excel (which populated dt) to your database.

    I see that you're calling da.Update(dt); Try opening a new dataset from the database, and going through the rows in dt, applying the changes to the rows in your new dataset. From what I can tell - and there's not much code there - no commands are issued because the dataadapter knows the internal rows of dt did not come from its datasource. That's my stab, anyway.