user2746526
user2746526

Reputation: 97

Update query fails to update rows value in DataGridView

I have a form, containing a button to add DataGridView rows and another button to delete the selected row. I'm using this code to save :

    private void SaveReq2()
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            this.mysql.sa.InsertCommand.CommandText = "INSERT INTO molaak_det(MAXID,MALKID,AKARTYPE,AKARADDRESS) VALUES ('" + this.dataGridView1.Rows[i].Cells[2].Value + "','" + txtID.Text + "','" + this.dataGridView1.Rows[i].Cells[0].Value + "','" + this.dataGridView1.Rows[i].Cells[1].Value + "')";
            mysql.sa.InsertCommand.ExecuteNonQuery();
        }
}

The save process works good but, when I want to update using the query, I'm updating only the current rows. If I insert a new row and then I have to update, the code saves this new row in the database. Here my UPDATE query :

    private void UpdateReq2()
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            mysql.sa.UpdateCommand.CommandText = string.Format(" UPDATE molaak_det SET  MALKID='{1}',AKARTYPE='{2}',AKARADDRESS='{3}' where MAXID='{0}'", this.dataGridView1.Rows[i].Cells[2].Value, txtID.Text, this.dataGridView1.Rows[i].Cells[0].Value, this.dataGridView1.Rows[i].Cells[1].Value);
            mysql.sa.UpdateCommand.ExecuteNonQuery();
        }
    }

Please, I need help to write well the UPDATE query. Thanks.

Upvotes: 0

Views: 283

Answers (2)

Alberto Solano
Alberto Solano

Reputation: 8227

I don't understand quite well your process.

You should execute, while adding a new row to the DataGridView, the INSERT query, because you cannot do this with an UPDATE query. Then, you have to understand in your control what rows have been added and proceed with the INSERT query.

Once this process completed, you can update the existing rows with an UPDATE query.

I agree with @PaulZahra, improve your queries using SqlParameter objects.

Upvotes: 0

BLoB
BLoB

Reputation: 9725

I suspect that your update command is trying to update data types incorrectly... first things first it is pretty unsecure, you should at least parameterise the sql...

Have a read of this tutorial / example on how to do it, it is pretty easy, must more secure and much more type safe than what you are doing. http://www.dotnetperls.com/sqlparameter

P.S. It helps if you could put details of any error, not just say it doesn't work... e.g is the power plug in on the DB server, is that why it doesn't work? :D

Upvotes: 1

Related Questions