更新DataGridView中的行

时间:2015-01-22 04:52:53

标签: c# datagridview

我正在尝试更新我的DataGridView。我只能更新一行,但当我尝试更新两行时,他们会给我一个错误:

  

“违反PRIMARY KEY约束”

string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
        string date = dt_date.Value.ToString("yyyy-MM-dd");
        var counter = 1;
            SqlConnection sc = new SqlConnection(strPRSconn);
            sc.Open();
            counter++;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {

            if (!row.IsNewRow)
            {

                    string strQry = "UPDATE CounterChecking "+
                    "SET part_no = @c0,po_no = @po_no,invoice = @invoice,part_name = @c1,"+
                    "date = @date,color = @c2,qty_ordered = @c3,qty_for_delivery = @c4,qty_recieved = @c5,"+
                    "variance = @c6,unit_price = @c7, total = @c8, remarks = @c9 "+
                    "WHERE po_no= '" + cb_po_search.Text + "'";
                    SqlCommand scmd = new SqlCommand(strQry, sc);
                    scmd.Parameters.AddWithValue("@c0", counter);
                    counter++;
                    scmd.Parameters.Add("@po_no", SqlDbType.VarChar).Value = tb_ponumber2.Text;
                    scmd.Parameters.Add("@invoice", SqlDbType.VarChar).Value = tb_invoice2.Text;
                    scmd.Parameters.AddWithValue("@c1", row.Cells[1].Value);
                    scmd.Parameters.Add("@date", SqlDbType.Date).Value = date;
                    scmd.Parameters.AddWithValue("@c2", row.Cells[2].Value);
                    scmd.Parameters.AddWithValue("@c3", row.Cells[3].Value);
                    scmd.Parameters.AddWithValue("@c4", row.Cells[4].Value);
                    scmd.Parameters.AddWithValue("@c5", row.Cells[5].Value);
                    scmd.Parameters.AddWithValue("@c6", row.Cells[6].Value);
                    scmd.Parameters.AddWithValue("@c7", row.Cells[7].Value);
                    scmd.Parameters.AddWithValue("@c8", row.Cells[8].Value);
                    scmd.Parameters.AddWithValue("@c9", row.Cells[9].Value);
                    scmd.ExecuteNonQuery();
                    sc.Close();
                    MessageBox.Show("Successfully Updated!");}
        }
    }    

0 个答案:

没有答案