How to reuse SqlCommand parameter through every iteration?

前端 未结 4 1960
暖寄归人
暖寄归人 2020-12-31 01:41

I want to implement a simple delete button for my database. The event method looks something like this:

private void btnDeleteUser_Click(object sender, Event         


        
4条回答
  •  渐次进展
    2020-12-31 02:44

    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.

提交回复
热议问题