I am trying to get shareholders current balance from table, then add for example, 10 percent to their current balance and then update the table back with the new balance, but i am getting error that says there is a connection not closed.
UPDATE: profit_percentage is a variable provided by the user.
try
{
var con = new SqlConnection(constr);
con.Open();
string stm = "SELECT * From shareholders_term";
var cmd = new SqlCommand(stm, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (rdr["current_balance"] != null)
{
num++;
int current_shareholder = Convert.ToInt32(rdr["shareholder_id"]);
current_balance = Convert.ToDecimal(rdr["current_balance"]);
decimal percentage = current_balance * profitpercentage / 100;
decimal new_balance = percentage + current_balance;
var cmdcurrentbalance = new SqlCommand(
"UPDATE shareholders_term SET profit_percentage = @percentage, current_balance = @new_balance WHERE shareholder_id = @current_shareholder",
con
);
cmdcurrentbalance.Parameters.AddWithValue("@percentage", profitpercentage);
cmdcurrentbalance.Parameters.AddWithValue("@new_balance", new_balance);
cmdcurrentbalance.Parameters.AddWithValue("@current_shareholder", current_shareholder);
cmdcurrentbalance.ExecuteNonQuery();
lblupdatecounter.Text = num + " - Shareholders updated.";
}
}
con.Close();
MessageBox.Show("Profit added to shareholders");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}