Record registration in DB

0
Hello, I'm having a Sql Server write problem, I have two tables (cargo and user), when I try to write the C # record, the error appears: (System.NullReferenceException: 'Object reference not set to an instance of an object. ' ObjectTransfer.User.Cargo.get returned null.)

My user table (IdCargo) references the cargo table (IdCargo and Description) so that the Combobox presents the available positions to choose from.

However, when trying to save stops on line as pictured and informs the error message, my program is done in layers.

I would like the help of the community to solve this error. Note: My Position Object is an object within an object.

Thank you!

BLL = Business layer for insertion

public String Inserir(Usuario usuario)
        {
            try
            {
                acessoBancoDeDadosSqlServer.LimparParametros();

                //acessoBancoDeDadosSqlServer.AdicionarParametros("@IdUsuario", usuario.IdUsuario);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@Nome", usuario.Nome);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@StatusUsu", usuario.StatusUsu);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@CPF", usuario.CPF);
                //acessoBancoDeDadosSqlServer.AdicionarParametros("@DataCadastro", usuario.DataCadastro);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@LoginUsu", usuario.LoginUsu);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@Senha", usuario.Senha);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@ConfirmarSenha", usuario.ConfirmarSenha);
                acessoBancoDeDadosSqlServer.AdicionarParametros("@IdCargo", usuario.Cargo.IdCargo);


                String idUsuario = acessoBancoDeDadosSqlServer.ExecutarManipulacao(CommandType.StoredProcedure, "uspUsuarioInserir").ToString();

                return idUsuario;
            }
            catch ( Exception exception )
            {
                return exception.Message;
            }

DTO = Transfer Object

namespace ObjetoTransferencia
{
    public class Usuario
    {
        public Int32 IdUsuario { get; set; }

        public String Nome { get; set; }

        public String CPF { get; set; }

        public DateTime DataCadastro { get; set; }

        public String LoginUsu { get; set; }

        public String Senha { get; set; }

        public String ConfirmarSenha { get; set; }       

        public Cargo Cargo { get; set; }

        public Boolean StatusUsu { get; set; }

    }

}

GUI = Presentation

private void toolStripSalvar_Click_1(object sender, EventArgs e)
        {
            Usuario usuario = new Usuario();

            usuario.CPF = Convert.ToString(maskedTextBoxCpf.Text);
            usuario.Nome = Convert.ToString(txtNome.Text).ToUpper();
            usuario.LoginUsu = Convert.ToString(txtLogin.Text);

            Cargo cargo = new Cargo();
            usuario.Cargo.IdCargo = Convert.ToInt32(usuario.Cargo.IdCargo);
            usuario.Cargo.Descricao = Convert.ToString(usuario.Cargo.Descricao);

            usuario.Senha = Convert.ToString(txtSenha.Text);
            usuario.ConfirmarSenha = Convert.ToString(txtConfirmarSenha.Text);

            if ( radioButtonAtivo.Checked == true)
            {
                usuario.StatusUsu = true;
            }
            else
            {
                usuario.StatusUsu = false;
            }

            UsuarioNegocios usuarioNegocios = new UsuarioNegocios();

            String retorno = usuarioNegocios.Inserir(usuario);

            try
            {
                Int32 idUsuario = Convert.ToInt32(retorno);

                MessageBox.Show("Usuário inserido com sucesso.\n\nCódigo: " + idUsuario.ToString(), "SUCESSO !", MessageBoxButtons.OK, MessageBoxIcon.Information);

                AtualizarGrid();
            }
            catch
            {
                MessageBox.Show("Não foi possível inserir registro.\n\nDetalhes: " + retorno, "ERRO !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

    
asked by anonymous 08.02.2018 / 15:20

3 answers

0

You are taking the values of the job definition itself, you instantiate the object and try to use the value itself, I believe that the IdCargo and the Description should come from another source, and technically for this logic would not need the Convert. ToInt32 and Convert.ToString because as it is getting from the same field are the same values.

        Cargo cargo = new Cargo();
        usuario.Cargo.IdCargo = Convert.ToInt32(usuario.Cargo.IdCargo);
        usuario.Cargo.Descricao = Convert.ToString(usuario.Cargo.Descricao);

Check your definition of the Cargo class if the IdCargo field is not nullable

        public class Cargo
        {
            public int? IdCargo {get; set;}
            public string Descricao { get; set; }
        }

I believe that if your logic is in accordance with what you want to remove Convert.ToInt32 will stop giving the exception.

        usuario.Cargo.IdCargo = Convert.ToInt32(usuario.Cargo.IdCargo);

for

        usuario.Cargo.IdCargo = usuario.Cargo.IdCargo;
    
08.02.2018 / 16:06
0

The cause of error is clear:

You instantiate a Usuario , begin filling user information, instantiate a Cargo - which is not having its properties filled - and attempts to populate a property of another object of type Cargo that is inside the user and has not yet been initialized from the information of the uninitialized object itself. It's a combo with two points where the zero reference exception will pop. Just at this point in your "presentation layer":

...
Cargo cargo = new Cargo();
usuario.Cargo.IdCargo = Convert.ToInt32(usuario.Cargo.IdCargo);
...

I think you intended to do something like this after initializing the job:

cargo.IdCargo = 1; // Algum valor válido com uma origem que faça sentido

But it's hard to say. This is a very messy scenario.

    
08.02.2018 / 16:22
0

If you want to pick combobox selection, you must do a direct conversion of the selected object. If the list that makes up the combobox is for positions, do so:

usuario.Cargo.IdCargo = ((Cargo)ComboBox1.SelectedItem).IdCargo;

Or even better:

usuario.Cargo = (Cargo)ComboBox1.SelectedItem;

You can still validate if the combobox has selection, otherwise it will fire exetion at the time of the direct conversion:

If(ComboBox1.SelectedItem != null)
{
   usuario.Cargo = (Cargo)ComboBox1.SelectedItem;
}
    
08.02.2018 / 16:43