首页 > 解决方案 > 在 Sqlcommand 中使用 Remove 和 RemoveAt

问题描述

我想使用方法 Remove 和 RemoveAT 从数据库中删除组合框中的值我总是看到使用方法 add 但现在我想要 remove 和 RemoveAT

cmd.Parameters.RemoveAt(comboBox1.SelectedIndex);

我写了这段代码,但代码中有错误

 private void Form1_Load(object sender, EventArgs e)
 {
     using(cnn = new SqlConnection(v))
     {
         using(cmd = new SqlCommand())
         {
             cmd.CommandText = "SELECT name_,age FROM Table_Group";
             cmd.Connection = cnn;
             cnn.Open();

             dr = cmd.ExecuteReader();

             while (dr.Read())
             {
                 comboBox1.Items.Add(dr["age"]);
             }

             dr.Close();
             cmd.Dispose();
             cnn.Close();
         }
    }
}

删除例程

 private void button5_Click(object sender, EventArgs e)
 {
     using (cnn = new SqlConnection(v))
     {
         using (cmd = new SqlCommand("DELETE FROM Table_Group WHERE age = @age", cnn))
         {
             cmd.Parameters.RemoveAt(comboBox1.SelectedIndex);
             cmd.Connection.Open();
             cmd.ExecuteNonQuery();
             cnn.Close();
             cmd.Dispose();
          }
      }
  }

标签: c#sql

解决方案


既然你想要

从数据库中删除组合框中的值

您应该添加参数(要删除的内容)而不是删除它。像这样的东西

using (var cnn = new SqlConnection(v)) { //TODO: don't you forget "var"?
  cnn.Open(); 
   
  // let's have sql being readable
  string sql = 
    @"DELETE 
        FROM Table_Group 
       WHERE age = @age";

  // using will Dispose for you; there's no need in Close() and Dispose()
  using (var cmd = new SqlCommand(sql, cnn)) {
    //TODO: cmd.Parameters.Add is a better syntax
    // I've put AddWithValue since I don't know corresponding RDBMS type
    cmd.Parameters.AddWithValue("@age", comboBox3.SelectedValue);
    cmd.ExecuteNonQuery();
  } 
}

RemoveAt如果要从组合框而不是数据库中删除,则可以使用:

// Remove Selected Value   
combobox3.RemoveAt(combobox3.SelectedIndex);

推荐阅读