C# Save Datatable-Object to MS-Access Database with SQL Update - Command

38 Views Asked by At

I save changes from my Datatableobject DT1 to my Access database, as can be seen in the following code. My problem is that I always have to run the last executing command a second time. Somehow it doesn't run correctly when run once. I have now fixed the problem in this way, but I would like to understand why that is. Does somebody has any idea?

Kind regards

foreach (DataRow DR1 in DT1.Rows)
                {
                    if (DR1.RowState == DataRowState.Modified | DR1.RowState == DataRowState.Added | DR1.RowState == DataRowState.Deleted) 
                    {
                        DA1.UpdateCommand = new OleDbCommand("UPDATE Table1 SET Column1 = @Column1, Column2 = @Column2 WHERE ID = @ID", Connection);
   
                        DA1.UpdateCommand.Parameters.Add("@Column1", OleDbType.VarChar).Value = DR1["Column1"];
                        DA1.UpdateCommand.Parameters.Add("@Column2 ", OleDbType.VarChar).Value = DR1["Column2 "]; 
                        DA1.UpdateCommand.Parameters.Add("@ID", OleDbType.VarChar).Value = DR1["ID"];

                        DA1.UpdateCommand.ExecuteNonQuery();
                    }
                    DA1.UpdateCommand.ExecuteNonQuery(); // Without this, the last command will not be executed
                }

0

There are 0 best solutions below