Error: Undefined object reference for an object instance of an Object.System.Formatexception

Asked

Viewed 87 times

0

I’m having a problem when it comes to excluding a client.

In the bank is deleted, but instead the message appears: "SUCCESSFULLY EXCLUDED!", message appears: "Could not delete".

Details:

Undefined object reference for an object instance. However, even with the message appearing, the record is deleted, but does not update, only updates when I click on search. However mine data grid loses all formatting.

I’m using Procedure and every excluded customer has the idCliente in return.

Erro capturado com mais detalhes

Method Excluir

public string Excluir(Cliente cliente)
    {   
        //tratamento de excessao
        try
        {
            acessoDadosSqlServer.LimparParametros();
            acessoDadosSqlServer.AdcionarParametros("@IdCliente", cliente.IdCliente);
           return acessoDadosSqlServer.ExecutarManipulacao(CommandType.StoredProcedure, "uspClienteExcluir").ToString();//COM PROCEDURE CODIGO SQL NO BANCO

           //return acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "DELETE FROM tblCliente WHERE IdCliente = @").ToString();//SEM PROCEDURE, CODIGO SQL NA PASSAGEM DE PARAMETROS

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

The event on the button excluir

private void buttonExcluir_Click(object sender, EventArgs e)
    {
        //1º VERIFICAR SE TEM REGISTRO SELECIONADO 
        if (dataGridViewPrincipal.SelectedRows.Count == 0)
        {
            MessageBox.Show("Nenhum cliente selecionado. ");
            return;
        }

        //2º PERGUNTAR SE REALMENTE QUER EXCLUIR 
        DialogResult resultado = MessageBox.Show("Deseja realmente excluir esse cliente?", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        //VERIFICANDO O RESULTADO COM CONDICIONAL
        if (resultado == DialogResult.No)
        {
            return;
        }

        //PEGAR CLIENTE SELECIONADO
        Cliente clienteSelecionado = dataGridViewPrincipal.SelectedRows[0].DataBoundItem as Cliente;

        //4º INSTANCIAR A REGRA DE NEGOCIO
        ClienteNegocios clienteNegocios = new ClienteNegocios();

        //CHAMAR O METODO EXCLUIR
        string retorno = clienteNegocios.Excluir(clienteSelecionado);

        //VERIFICAR SE EXCLUIU COM SUCESSO
        try
        {
            int idCliente = int.Parse(retorno);//verificando se a string tem o valor int
            MessageBox.Show("Cliente Excluido com sucesso", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //ATUALIZAR O GRID, POIS SÓ EXCLUIR ELE NAO SOME DO GRID NA HORA.
            AtualizarGrid();
        }
        catch
        {
            MessageBox.Show("Não foi possível, excluir. Detalhes: "+ retorno  , "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

Procedure to exclude:

BEGIN
DELETE FROM 
    tblCliente
WHERE
    IdCliente = @IdCliente
END

1 answer

1


Note that the message indicates that the error occurred in the event buttonExcluir_Click(), in the call to method System.Int32.Parse(String s). Looking at your code, it seems to me that line is causing the error:

int idCliente = int.Parse(retorno); //verificando se a string tem o valor int

And the error that is occurring is of the type FormatException, indicating that the value string is not in a suitable format for conversion to type int32. Have you checked which value is being returned by the method clienteNegocios.Excluir()?

The method int.Parse() returns the value int, result of the conversion of a value string, but makes an exception if conversion is not possible.

In that case I suggest you use the method int.TryParse(), that returns a Boolean stating whether the conversion was successful or not, rather than making an exception in the event of a conversion failure.

The code could be written this way:

int idCliente;
bool sucesso = int.TryParse(retorno, out idCliente);

The result of the conversion of string for int is returned through the output parameter result (the second parameter in the method).

  • It worked perfectly, after making these changes to the code as I said. Thank you very much! In question the formatting of the data grid header, I keep losing every update

  • @user122926, the best way to thank for an answer is to mark it as accepted by clicking on the visa sign ( ). But do this only when any answer has answered your original question. When you reach 15 reputation points you can also vote in favour of an answer or question. See: Someone answered me and Why vote?. Also do the [tour], for an initial explanation of how the site works.

  • On the problem of grid formatting, post another question about this, with the code related to the problem, because there is another question about another problem. If you want you can even refer to this question, with a link to it.

Browser other questions tagged

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