Tôi muốn thực hiện một nút xóa đơn giản cho cơ sở dữ liệu của tôi. Phương thức sự kiện trông giống như sau:Làm thế nào để tái sử dụng tham số SqlCommand thông qua mỗi lần lặp?
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;
}
}
nhưng tôi nhận được tin nhắn này:
Một @ id biến đã được công bố. Tên biến phải là duy nhất trong vòng lô truy vấn hoặc quy trình được lưu trữ.
Có cách nào để sử dụng lại biến này không?