0

i want to save the rows of dataGridview into database. i am using button_click event. when i press the button it gives me the following error: "Fatal error encountered during command execution."

here is the code which i am using:

private void save_Click(object sender, EventArgs e)
{
    con.Open();

    string str = "insert into cash_in_accounts (cr_id, acc_no, acc_name, amount, description) values (" + rid.Text + ",@accno, @accname, @amnt, @desc)";
    for (int row = 0; row < dataGridView1.Rows.Count -1; row++)
    {
        MySqlCommand cmd2 = new MySqlCommand(str, con);

        cmd2.Parameters.AddWithValue("@accno", dataGridView1.Rows[row].Cells[0].FormattedValue.ToString());
        cmd2.Parameters.AddWithValue("@accname", dataGridView1.Rows[row].Cells[1].FormattedValue.ToString());
        cmd.Parameters.AddWithValue("@desc", dataGridView1.Rows[row].Cells[2].FormattedValue.ToString());
        cmd2.Parameters.AddWithValue("@amnt", dataGridView1.Rows[row].Cells[3].FormattedValue.ToString());                

        cmd2.ExecuteNonQuery();
    }

    con.Close();
}
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Haider Khattak
  • 567
  • 3
  • 8
  • 32

1 Answers1

0

Why are you using the loop? As I think there is no use of loop, every time you click on the button the data will automatically save in the database and also if you want to insert the data again and again then also you have click on the button because if you didn't the values will be same on every time when the command will be execute.

Your Code should be :

con.Open();

string str = "insert into cash_in_accounts (cr_id, acc_no, acc_name, amount, description) values (" + rid.Text + ",@accno, @accname, @amnt, @desc)";


    MySqlCommand cmd2 = new MySqlCommand(str, con);

    cmd2.Parameters.AddWithValue("@accno", dataGridView1.Rows[row].Cells[0].FormattedValue.ToString());
    cmd2.Parameters.AddWithValue("@accname", dataGridView1.Rows[row].Cells[1].FormattedValue.ToString());
    cmd.Parameters.AddWithValue("@desc", dataGridView1.Rows[row].Cells[2].FormattedValue.ToString());
    cmd2.Parameters.AddWithValue("@amnt", dataGridView1.Rows[row].Cells[3].FormattedValue.ToString());                

    cmd2.ExecuteNonQuery();

con.Close();