My delete button is giving error expects the Parameter

Asked

Viewed 72 times

4

When I try to make a DELETE the following message is appearing:

inserir a descrição da imagem aqui

My code:

private void BtnExcluir_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Confirma a Exclusão desses Registros?", "Atenção",
              MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        conexao.ConnectionString = strconexao;
        cmd.Connection = conexao;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "DELETE FROM PRODUTOS WHERE CODPROD =Codigo";

        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@Codigo", chaveID);
        try
        {
            conexao.Open();
             cmd.ExecuteNonQuery();
             MessageBox.Show("Registros Excluidos com Sucesso!!!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString(), "Atenção");
        }
        finally
        {
            if (conexao.State == ConnectionState.Open)
            {
                conexao.Close();
                MontarLista();

                LimparFormulario();
                BtnExcluir.Enabled = true;
            }
         }
    }
}               
  • You can edit your question and put the code that makes this operation?

  • Sorry I can’t post right here yet

1 answer

0

I made some changes.

1. I arranged the @ missing from query.

2. I created a new instance pro Sqlcommand.

private void BtnExcluir_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Confirma a Exclusão desses Registros?", "Atenção",
              MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        string sqlQuery = "DELETE FROM PRODUTOS WHERE CODPROD = @Codigo;";

        using (SqlConnection conexao = new SqlConnection(strconexao))
        {
            SqlCommand command = new SqlCommand(sqlQuery, conexao);
            command.Parameters.AddWithValue("@Codigo", chaveID);
            try
            {
                conexao.Open();
                command.ExecuteNonQuery();
                MessageBox.Show("Registros Excluidos com Sucesso!!!");

                MontarLista();

                LimparFormulario();
                BtnExcluir.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Atenção");
            }
        }
    }
}        

Browser other questions tagged

You are not signed in. Login or sign up in order to post.