Object cannot be converted to dbnull in other types

Asked

Viewed 2,001 times

0

Good afternoon gentlemen.

I am making a user registration in the college work and when logging in this error appears.

How can I solve?

<code>ERRO</code>

    private Usuario Mapear(DataRow registro)
    {
        var usuario = new Usuario();

        usuario.Nome = Convert.ToString(registro["NOME"]);
        usuario.Senha = Convert.ToString(registro["SENHA"]);
        usuario.Email = Convert.ToString(registro["EMAIL"]);
        usuario.Telefone = Convert.ToString(registro["TELEFONE"]);
        usuario.Status = (Status)Convert.ToInt32(registro["STATUS"]);
        //usuario.Funcao = Convert.ToString(registro["FUNCAO"]);
        //usuario.Setor = Convert.ToString(registro["SETOR"]);

        return usuario;
    }

I don’t know how to proceed. I’ve tried almost everything.

Erro

  • What value is this field registro["STATUS"] returns?

  • 1

    Don’t use high-end, young man. It’s ugly, kkkkk

  • Probably the data ( record["STATUS"]) is returning a null value, so it is not possible to convert to int. Just to confirm, before converting display what is being brought, so we can check

  • 1

    Use an ORM, don’t waste time.

1 answer

1


The field in question is returning Dbnull and you try to convert it to integer.

Do checks before a conversion:

public static  Usuario Mapear(DataRow registro)
{
    var usuario = new Usuario();
    usuario.Nome = Convert.ToString(registro["NOME"]);

    if (registro["STATUS"] != DBNull.Value)
        usuario.Status = (Status)Convert.ToInt32(registro["STATUS"]);
    else 
        usuario.Status = Status.status2; //se vier null, faça algo

    return usuario;
}

Example in . Netfiddle

Browser other questions tagged

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