DataGridView更新数据库

时间:2013-08-27 07:24:38

标签: c# windows forms

当我使用下面的代码时,循环迭代两次,我收到错误消息“变量名'@ projectName1'已经被声明。变量名在查询批处理或存储过程中必须是唯一的。”并重置datagridview和表中的表的所有值。实际上我想通过选择单元格来更新表单中的DataGridView,它也应该在数据库中反映出来。

 private void btnUpdate_Click(object sender, EventArgs e)
        {
            SqlConnection con = Helper.getconnection();
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            string myCmd = string.Empty;
            foreach (DataGridViewRow myDgrow in dataGridView2.Rows)
            {
                myCmd = "Update Details set ProjectName='" + myDgrow.Cells["ProjectName"].Value + "', Description = '" + myDgrow.Cells["Description"].Value + "', DateStarted='" + myDgrow.Cells["DateStarted"].Value + "',TeamSize='" + myDgrow.Cells["TeamSize"].Value + "',Manager='" + myDgrow.Cells["Manager"].Value + "'";
                cmd.Parameters.AddWithValue("@projectName1", myDgrow.Cells["ProjectName"].Value);
                cmd.Parameters.AddWithValue("@Description1", myDgrow.Cells["Description"].Value);
                cmd.Parameters.AddWithValue("@DateStarted1", myDgrow.Cells["DateStarted"].Value);
                cmd.Parameters.AddWithValue("@TeamSize1", myDgrow.Cells["TeamSize"].Value);
                cmd.Parameters.AddWithValue("@Manager1", myDgrow.Cells["Manager"].Value);
                cmd.CommandText = myCmd;
               cmd.ExecuteNonQuery();
                dataGridView2.Update();
                myCmd = string.Empty;
            }
DataTable details = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter();
            try
            {
                da.Update(details);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }

1 个答案:

答案 0 :(得分:5)

您正在使用foreach循环并且每次都将参数添加到同一命令。每次循环迭代时清除参数或每次都创建一个新命令..