How to reuse SqlCommand parameter through every iteration?

前端 未结 4 1966
暖寄归人
暖寄归人 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:27

    Error is because you are adding the same parameter again and again in each iteration of the loop.

    I would move that code to a seperate method so that i can call it from multiple places as needed.

    public bool DeleteUser(int userId)
    {
        string connString = "your connectionstring";
        try
        {
          using (var conn = new SqlConnection(connString))
          {
            using (var cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "DELETE FROM tbl_Users WHERE userID = @id";
                cmd.Parameters.AddWithValue("@id", userId);
                conn.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
          }
        }
        catch(Exception ex)
        {
          //Log the Error here for Debugging
          return false;
        }
    
    }
    

    Then call it like this

     foreach (DataGridViewRow row in dgvUsers.SelectedRows)
     {
       int selectedIndex = row.Index;
       if(dgvUsers[0,selectedIndex]!=null)
       {
         int rowUserID = int.Parse(dgvUsers[0,selectedIndex].Value.ToString());
         var result=DeleteUser(rowUserID)
       }
       else
       {
          //Not able to get the ID. Show error message to user
       } 
     }
    

提交回复
热议问题