You need to capture all the numbers on the loop before inserting it on the database. You don't want to do the database update inside the loop since this, I think, might cause an overhead on your database. What you can probably do is insert a logic that will get all the numbers while loop is running and store it on a collection. And then, put the values of the collection as parameters on an
SqlDataCommand
, and then do the database update.
[Update to OP's follow up question]
Here is one way you might want to do. Basically, inside the loop, you add all the parameters in a collection, like a dictionary, for example.
Dictionary<string, string> param = new Dictionary<string, string>();
while(itr.MoveNext())
{
param.Add("@parameterName", "value");
}
After gathering all the required parameter values, you now add them on the parameters of your
SqlCommand
. See the following example.
string query = "INSERT INTO YourTable (col1, col2, col3, etc....) VALUES(@val1, @val2, @val3, etc...)";
SqlConnection conn = new SqlConnection("Your connection string");
SqlCommand comm = new SqlCommand(query, conn);
foreach (KeyValuePair<string, string> keyVal in param)
{
comm.Parameters.AddWithValue(keyVal.Key, keyVal.Value);
}
comm.ExecuteNonQuery();
Of course this will not work for you. You have to tailor it to suit your scenario. But I hope you get the idea now.