为什么这不起作用?当我尝试删除某些内容时,它说无效的列名

    private void btnRemoveCommand_Click(object sender, EventArgs e)
    {
        connection = new SqlConnection(connectionString);
        connection.Open();

        for (int i = 0; i < listBox1.SelectedItems.Count; i++)
        {
            var sql = "DELETE FROM Commands WHERE commandName = " + listBox1.SelectedItems[i] + "";

            listBox1.Items.Remove(listBox1.SelectedItems[i]);
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.ExecuteNonQuery();
        }
        connection.Close();
    }

这是处理添加命令到数据库的事件
private void btnAddCommand_Click(object sender, EventArgs e)
{
   var sql = "INSERT INTO Commands(commandName, pathToCommand) VALUES(@commandName, @pathToCommand)";
                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    SqlCommand cmd = new SqlCommand(sql, connection);

                    cmd.Parameters.AddWithValue("@commandName", tbxCommand.Text);
                    cmd.Parameters.AddWithValue("@pathToCommand", tbxPathToCommand.Text);

                    int affectedRows = cmd.ExecuteNonQuery();
                }
}

最佳答案

更改

var sql = "DELETE FROM Commands WHERE commandName = " + listBox1.SelectedItems[i] + "";




var sql = "DELETE FROM Commands WHERE commandName = '" + listBox1.SelectedItems[i] + "'";

10-08 02:17