Click here to Skip to main content
15,910,886 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this code that should update a row in a table from a database.
The query works if I write it in SQL server directly as a query, but it doesn't work from a C# context. Can somebody please explain me what I should do to make this work:

this is my code:

C#
//Pas huidig saldo kassa aan:
        public void huidigSaldoKassaAanpasser(int kassaID, double bedrag)
        {

            SqlTransaction transactie = null;
            try
            {
                if (connectie.State == System.Data.ConnectionState.Closed)
                {
                    connectie.Open();
                }
                transactie = connectie.BeginTransaction();
                SqlCommand cmdHaalGegevensOp = new SqlCommand(@"Update Kassa SET huidigsaldo = @bedrag
                                                                      WHERE id = @kassaID");
                cmdHaalGegevensOp.Connection = connectie;
                cmdHaalGegevensOp.Transaction = transactie;
                cmdHaalGegevensOp.Parameters.AddWithValue("@kassaID", kassaID);
                cmdHaalGegevensOp.Parameters.AddWithValue("@bedrag", bedrag);
                cmdHaalGegevensOp.ExecuteNonQuery();
               
            }
            catch (Exception ex)
            {
                if (transactie != null)
                {
                    transactie.Rollback();
                }
                throw ex;
            }
            finally
            {
                connectie.Close();
            }
        }


Unfortianetly everytime i run this code, I get no exceptions but the row isn't updated. The int kassaID and the double bedrag are correct.

If I write it as this in SQL server management studio as a new Query:

Update Kassa SET huidigsaldo = 598 WHERE id = 7;

everything works fine.
Posted

It is never updated because you do not Commit the transaction - you just close it. After the ExecuteNoQuery call, add the line:
C#
transactie.Commit();
 
Share this answer
 
Comments
the original stinger 28-Feb-12 7:22am    
Thank you, must have looked over that statement.
OriginalGriff 28-Feb-12 7:46am    
Easy to do! :laugh:
can you tell me the type of "huidigsaldo" field in the database, if it is an int, you have to convert parameter "bedrag" to in when you are adding , see code as below

C#
cmdHaalGegevensOp.Parameters.AddWithValue("@bedrag",Convert.ToInt32(bedrag));
 
Share this answer
 
Comments
the original stinger 28-Feb-12 7:22am    
it was a money type so that's why it was a double.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900