I want to implement a simple delete button for my database. The event method looks something like this:
private void btnDeleteUser_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure?", "delete users",MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { command = new SqlCommand(); try { User.connection.Open(); command.Connection = User.connection; command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id"; int flag; foreach (DataGridViewRow row in dgvUsers.SelectedRows) { int selectedIndex = row.Index; int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString()); command.Parameters.AddWithValue("@id", rowUserID); flag = command.ExecuteNonQuery(); if (flag == 1) { MessageBox.Show("Success!"); } dgvUsers.Rows.Remove(row); } } catch (SqlException ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { if (ConnectionState.Open.Equals(User.connection.State)) User.connection.Close(); } } else { return; } }
but I get this message:
A variable @id has been declared. Variable names must be unique within a query batch or stored procedure.
Is there any way to reuse this variable?
In this case, you can reuse the command, but you shouldn't clear the parameters -- just add them once and explicitly set all values that change in every iteration instead.
Command objects use parameters to pass values to SQL statements or stored procedures, providing type checking and validation. Unlike command text, parameter input is treated as a literal value, not as executable code.
Parameters. Clear()". This will clear out all of the parameters so that you can add some new ones.
AddWithValue replaces the SqlParameterCollection. Add method that takes a String and an Object. The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.
Parameters.AddWithValue
adds a new Parameter to the command. Since you're doing that in a loop with the same name, you're getting the exception "Variable names must be unique".
So you only need one parameter, add it before the loop and change only it's value in the loop.
command.CommandText = "DELETE FROM tbl_Users WHERE userID = @id"; command.Parameters.Add("@id", SqlDbType.Int); int flag; foreach (DataGridViewRow row in dgvUsers.SelectedRows) { int selectedIndex = row.Index; int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString()); command.Parameters["@id"].Value = rowUserID; // ... }
Another way is to use command.Parameters.Clear();
first. Then you can also add the parameter(s) in the loop without creating the same parameter twice.
Rather than:
command.Parameters.AddWithValue("@id", rowUserID);
Use something like:
System.Data.SqlClient.SqlParameter p = new System.Data.SqlClient.SqlParameter();
Outside the foreach, and just set manually inside the loop:
p.ParameterName = "@ID"; p.Value = rowUserID;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With