Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse SqlCommand parameter through every iteration?

Tags:

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?

like image 614
miller Avatar asked Aug 23 '12 21:08

miller


People also ask

Can you reuse SqlCommand?

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.

Which object is used to pass variable to SqlCommand?

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.

How do you clear a parameter in C#?

Parameters. Clear()". This will clear out all of the parameters so that you can add some new ones.

What is SqlCommand parameters AddWithValue?

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.


2 Answers

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.

like image 159
Tim Schmelter Avatar answered Sep 17 '22 13:09

Tim Schmelter


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; 
like image 24
Cashley Avatar answered Sep 19 '22 13:09

Cashley