karthik reddy
karthik reddy

Reputation: 454

DataGridView Updating database

When I use the following code the loop is iterating twice and I am getting error message as "The variable name '@projectName1' has already been declared. Variable names must be unique within a query batch or stored procedure." and resetting all the values of the table in the datagridview as well as in the table. Actually I want to update the DataGridView in the form itself by selecting the cell and it should reflect the same in the database too.

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

Upvotes: 2

Views: 419

Answers (1)

AsitK
AsitK

Reputation: 673

You are using foreach loop and adding the parameters each time to the same command. Either clear the parameters each time you iterate in the loop or create a new command each time..

Upvotes: 5

Related Questions