A set of .NET Framework managed libraries for developing graphical user interfaces.
Hi Ron,
I had started writing a reply to you yesterday and this morning, but my computer crashed and I lost the whole reply. And of course, I hadn't saved anything! Grrr.
Anyway, as @Daniel Zhang-MSFT said, your code will work just fine (the transaction.Commit() will complete before the myDT_Clients.Clear() statement executes).
If you recall, I had mentioned the use of TransactionScope instead of SqlTransaction in my comment. It will make your code a bit cleaner (in my opinion). Here is what your code would look like if you used TransactionScope:
See my blogpost for the code for the static GetTransactionScope() in a Utils class and the reason why I've done it this way instead of just new TransactionScope()
https://geek-goddess-bonnie.blogspot.com/2010/12/transactionscope-and-sqlserver.html
using (TransactionScope scope = Utils.GetTransactionScope())
using (SqlConnection connection = new SqlConnection(dbConnectionString)) // you can "stack" usings like this
{
try
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.Connection = connection;
// won't need these now
// transaction = connection.BeginTransaction();
// command.Transaction = transaction;
// This can go outside the loop.
command.CommandText = "UPDATE Clients SET Name=@Name WHERE ClientID=@ClientID)";
foreach (DataRow drow in myDT_Clients.Rows)
{
command.Parameters.Add("@Name", SqlDbType.VarChar).Value = drow["Name"];
command.Parameters.Add("@ClientID", SqlDbType.BigInt).Value = drow["clientID"];
command.ExecuteNonQuery();
command.Parameters.Clear();
}
//transaction.Commit();
scope.Complete();
myDT_Clients.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!");
// You won't need the try/catch or the Rollback.
// If the TransactionScope using block can't execute with an exception
// the transaction is automatically rolled back. In fact there is no
// Rollback or similar command in TransactionScope, because it's not needed.
//try
//{
// transaction.Rollback();
//}
//catch (Exception ex2)
//{
// MessageBox.Show(ex2.Message, "Rollback Error!");
//}
}
}
Give it a try if you'd like.