Save BD register

Asked

Viewed 59 times

0

Hello, I am having a write problem in Sql Server, I have two tables(post and user), when I try to save the C#record, the error appears: (System.Nullreferenceexception: 'Object Reference not set to an instance of an Object. ' Objectcransference.Usuario.Cargo.get returned null.)

My user table (Idcargo) refers to the position table (Idcargo and Description) so that Combobox presents the available positions for choice.

However, when trying to write stops on the line as per photo and informs the error message, my program is layered.

I would like the help of the community to solve this mistake. NOTE: My Cargo Object, is as object inside object.

Grateful !!

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 = Object Transfer

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);
            }


        }

inserir a descrição da imagem aqui

  • debug your code and pay attention to the rank and file, because Idcargo comes from where? Another notorious thing is the number of Convert.To, since when the property .text of TextBox and MaskTextBox already return string. You are instantiating Cargo, if it does not feed Cargoid in the constructor,, soon it will be null. Put your Cargo class!!!

  • Change sea class User to have a constructor initialize Cargo.

  • Vagner, in that case, it would be interesting to accept the answer that provided the solution to help others in the community who have at least a problem. I believe it was @Therafa’s

3 answers

0

You’re taking the values of the very definition of a position, you instantiate the Object and you try to use the very value of it, I believe Idcargo and Descricao should come from another source, and technically for this logic would not be necessary Convert.Toint32 and Convert.Tostring because as you are picking up 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 Position class definition if the Idcargo field is not invalid

        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 already stop giving the exception.

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

for

        usuario.Cargo.IdCargo = usuario.Cargo.IdCargo;
  • Guys, thank you so much for all your help. I only had to inform where I would store the information as I was informed: If(Combobox1.Selectedit != null) { user.Cargo = (Job)Combobox1.Selectedit; } This has solved my problem. Very grateful indeed.

0

The cause of error is clear:

You instancia a Usuario, starts filling in user information, instance a Cargo - that is not having its properties filled - and tries to fill in a property of another object of the type Cargo which is within the user and has not yet been initialized from the information of the own uninitialized object. It is a combo with two points where will burst the null reference Exception. Just at this point of its "presentation layer":

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

I believe you intended to do something like this after you initialized the post:

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

But it’s hard to say. This scenario of yours is pretty messed up.

0

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

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

Or better yet:

usuario.Cargo = (Cargo)ComboBox1.SelectedItem;

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

If(ComboBox1.SelectedItem != null)
{
   usuario.Cargo = (Cargo)ComboBox1.SelectedItem;
}

Browser other questions tagged

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