更新查询无法更新DataGridView中的行值

时间:2013-10-28 08:29:58

标签: c# .net sql

我有一个表单,其中包含一个用于添加DataGridView行的按钮和另一个用于删除所选行的按钮。我正在使用此代码保存:

    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();
        }
}

保存过程运行良好但是,当我想使用查询更新时,我只更新当前行。如果我插入一个新行然后我必须更新,代码会将这个新行保存在数据库中。这是我的UPDATE查询:

    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();
        }
    }

请我帮忙写好UPDATE查询。感谢。

2 个答案:

答案 0 :(得分:1)

我怀疑你的更新命令正在尝试错误地更新数据类型...首先它首先是非常不安全的,你至少应该参数化sql ......

阅读本教程/示例,了解如何操作,它非常简单,必须更安全,并且比您正在做的更安全。 http://www.dotnetperls.com/sqlparameter

P.S。它可以帮助您提供任何错误的详细信息,而不仅仅是说它不起作用......例如,数据库服务器上的电源插头,这就是为什么它不起作用? :d

答案 1 :(得分:0)

我不太了解你的过程。

您应该在向DataGridView添加新行时执行INSERT查询,因为您无法使用UPDATE查询执行此操作。 然后,您必须在控件中了解添加了哪些行并继续执行INSERT查询。

完成此过程后,您可以使用UPDATE查询更新现有行。

我同意@PaulZahra,使用SqlParameter对象改进您的查询。