Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to update whole datatable in c# connected to access(oledb) using for loop, datatable is ok, connection is ok, the problem is, update just runs on first row and other rows are unchanged. here is my code:

OleDbCommand1.CommandText = "UPDATE data Set [pivot] =@pivot WHERE [ID] = @id";
           for (int i = 0; i < n; i++)
           {

               float OP =float.Parse(dt.Rows[i]["openPrice"].ToString());
               float CP = float.Parse(dt.Rows[i]["closePrice"].ToString());
               float HP = float.Parse(dt.Rows[i]["highPrice"].ToString());

               pivotValue = (OP + CP + HP) / 3;
               pivotValueString = pivotValue.ToString();

               OleDbCommand1.Parameters.AddWithValue("@pivot", pivotValueString);
               OleDbCommand1.Parameters.AddWithValue("@id", int.Parse(dt.Rows[i]["ID"].ToString()));

              // OleDbCommand1.CommandText = "UPDATE data Set [pivot] =@pivot WHERE [ID] = @id";

               OleDbCommand1.ExecuteNonQuery();



           }


What I have tried:

I changed the place of OleDbCommand1.CommandText , inside and outside of for loop, but nothing changed.
I will be glad if anybody helps.
Posted
Updated 11-Dec-19 3:54am
Comments
ZurdoDev 11-Dec-19 8:19am    
Debug it and find out what is happening. For example, check int.Parse(dt.Rows[i]["ID"].ToString() every time it runs through the loop.

You also need to clear your parameters inside the loop since you always call AddWithValue. OleDbCommand1.Parameters.Clear();

Just do some basic debugging and you should be able to find out very quickly what's going on.
sepidehGandom 11-Dec-19 23:59pm    
Thanks a lot, it worked, I did not know this code, you really saved my energy
Richard MacCutchan 11-Dec-19 11:00am    
Why are you converting values to strings just so you can convert them back to numbers? And you should not use floats for financial values; use int or decimal types.

1 solution

Try;

OleDbCommand1.Parameters.Clear();
OleDbCommand1.Parameters.AddWithValue("@pivot", pivotValueString);
OleDbCommand1.Parameters.AddWithValue("@id", int.Parse(dt.Rows[i]["ID"].ToString()));
 
Share this answer
 

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