How to reuse SqlCommand parameter through every iteration?

前端 未结 4 1933
暖寄归人
暖寄归人 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
       } 
     }
    
    0 讨论(0)
  • 2020-12-31 02:36

    I would use this:

    public static class DbExtensions
    {
        public static void AddParameter(SQLiteCommand command, string name, DbType type, object value)
        {
            var param = new SQLiteParameter(name, type);
            param.Value = value;
            command.Parameters.Add(param);
        }
    }
    

    Then, call this:

    DbExtensions.AddParameter(command, "@" + fieldOfSearch[i], DbType.String, value[i]);
    
    0 讨论(0)
  • 2020-12-31 02:43

    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;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题