Object can not be converted to dbnull in other types

0

Good evening, gentlemen.

I am doing a user registration in college work and at logar this error appears.

How can I resolve?

privateUsuarioMapear(DataRowregistro){varusuario=newUsuario();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 do not know how to proceed. I've tried almost everything.

    
asked by anonymous 24.10.2018 / 17:58

1 answer

1

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

Check 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

    
24.10.2018 / 19:28