c# - DataGridView 更新数据库

标签 c# windows forms

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

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

最佳答案

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

关于c# - DataGridView 更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459416/

相关文章:

javascript - 在 JS 调用上执行 PHP 的可靠方法?

c# - 在 DataTemplate 中显示数据绑定(bind)的 StackPanel

c# - Ubuntu上的Unity/C#和Python通信

c++ - 抱歉,未实现 : 64 bit mode not compiled in

Python BaseHTTP服务器 : How to get it to stop?

javascript - 如何在 ReactJS 中处理多个选择表单

forms - 在 Symfony2 表单中插入 Google Recaptcha

c# - 动态添加的 DropDownlists 未触发 SelectedIndexChanged 事件

c# - 使用 CaSTLe Windsor 解析具有泛型类型约束的接口(interface)

c# - .NET Core MVC Web 应用程序从查询字符串而不是模型获取值