Null reference, I made a check before inserting the values and the error continues

0

I'm having this error when in my program we have two classes with methods referenced.

  

System.NullReferenceException was unhandled             HResult = -2147467261             Message = Object reference not set to an instance of an object.             Source = Programming in Business Languages             StackTrace:                  at Program_in_Commercial_Languages.FormCadastroUsuario.button1_Click (Object sender, EventArgs e) in d: \ users \ lucas \ documents \ visual studio 2015 \ Projects \ Programming in Commercial Languages \ Programming in Commercial Languages \ Screen_Cadastro_Usuario.cs: line 63                  at System.Windows.Forms.Control.OnClick (EventArgs and)                  at System.Windows.Forms.Button.OnClick (EventArgs and)                  at System.Windows.Forms.Button.OnMouseUp (MouseEventArgs mevent)                  at System.Windows.Forms.Control.WmMouseUp (Message & m, MouseButtons button, Int32 clicks)                  at System.Windows.Forms.Control.WndProc (Message & m)                  at System.Windows.Forms.ButtonBase.WndProc (Message & m)                  at System.Windows.Forms.Button.WndProc (Message & m)                  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage (Message & m)                  at System.Windows.Forms.Control.ControlNativeWindow.WndProc (Message & m)                  at System.Windows.Forms.NativeWindow.DebuggableCallback (IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)                  at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW (MSG & msg)                  at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)                  at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner (Int32 reason, ApplicationContext context)                  at System.Windows.Forms.Application.ThreadContext.RunMessageLoop (Int32 reason, ApplicationContext context)                  at System.Windows.Forms.Application.Run (Form mainForm)                  at Program_in_Commercial_Messages.Program.Main () in d: \ users \ lucas \ documents \ visual studio 2015 \ Projects \ Programming in Commercial Languages \ Programming in Commercial Languages \ Program.cs: line 19                  at System.AppDomain._nExecuteAssembly (RuntimeAssembly assembly, String [] args)                  at System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] args)                  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ()                  at System.Threading.ThreadHelper.ThreadStart_Context (Object state)                  at System.Threading.ExecutionContext.RunInternal (ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)                  at System.Threading.ExecutionContext.Run (ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)                  at System.Threading.ExecutionContext.Run (ExecutionContext executionContext, ContextCallback callback, Object state)                  at System.Threading.ThreadHelper.ThreadStart ()             InnerException:

The error occurs when I am trying to write the User.login.login field in the database, it goes through the part that writes User.name and when it arrives at that would be User.login.login it gives this error, would you tell me what I am doing wrong? The code is auto incremented in the database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
    public class Login
    {
        public Login() { }
        public String login;
        public String senha;
        public bool tipo; 
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
    class Usuario
    {
        public Usuario() { }
        public int codigo;
        public String nome;
        public Login login;       
    }

The part that has the error, in it I check with the IF to see if any of the fields are not empty. I do not know why it keeps returning this error message if if will never happen if any of the fields are empty.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Programacao_em_Linguagens_Comerciais
{
    public partial class FormCadastroUsuario : Form
    {
        public FormCadastroUsuario()
        {
            InitializeComponent();
        }
        public void FormCadastroUsuario_Load(object sender, EventArgs e)
        {
        }
        public void label1_Click(object sender, EventArgs e)
        {
        }
        public void textBox3_TextChanged(object sender, EventArgs e)
        {
        }
        public void textBox2_TextChanged(object sender, EventArgs e)
        {
        }
        public void textBox1_TextChanged(object sender, EventArgs e)
        {
        }
        public void textBox4_TextChanged(object sender, EventArgs e)
        {
        }
        public void textBox5_TextChanged(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Usuario Entrada = new Usuario();
            new CadastroUsuarioService().Gravar(Entrada);
                if (TXTCadastroUsuarioNome.Text != "" && TXTCadastroUsuarioLogin.Text != "" && TXTCadastroUsuarioSenha.Text != "")
                {
                    Entrada.nome = TXTCadastroUsuarioNome.Text;
                    Entrada.login.login = TXTCadastroUsuarioLogin.Text;
                    Entrada.login.senha = TXTCadastroUsuarioSenha.Text;
                    MessageBox.Show("usuario cadastrado.");
                } 
           // MessageBox.Show("Autenticacao efetuada com sucesso");
           // this.Hide();
            //FormCadastroUsuario Tela = new FormCadastroUsuario();
            //Tela.Visible = true;   
          //  MessageBox.Show("Falha na autenticacao");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Programacao_em_Linguagens_Comerciais
{
    class CadastroUsuarioService
    {
        public void Gravar(Usuario usuario)
        {
            new CadastroUsuarioDAO().Gravar(usuario);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Web;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace Programacao_em_Linguagens_Comerciais
{
    class CadastroUsuarioDAO
    {
        MySqlConnection conn = null;
        private String connectionString = "Server=localhost;Database=DB_Atps_Prog_Ling_Comerc;Uid=Lucas;Pwd=123;";
        public CadastroUsuarioDAO()
        {
            OpenCon();
        }
        public void OpenCon()
        {
            if (conn == null)
            {
                conn = new MySqlConnection(connectionString);
            }
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }
        }
        public void CloseCon()
        {
            if (conn != null && conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }
        public void Gravar(Usuario usuario)
        {
            try
            {
                if (usuario.nome != "" && usuario.login.login != "" && usuario.login.senha != "")
                {
                    String comandoMysql = "insert into Usuario(nome,login,senha)"
       + "values ('" + usuario.nome + "','" + usuario.login.login + "','" + usuario.login.senha + "')";
                    MySqlCommand cmd = new MySqlCommand(comandoMysql, conn);
                    //   cmd.ExecuteNonQuery();
                }
                else
                {
                }
            }
            catch
            {
            }
        }
    }
}
    
asked by anonymous 29.11.2015 / 01:11

1 answer

1

You need to instantiate a login and put it inside the user, a good way to do this would be to use the user constructor:

public Usuario(Login login) {
    this.login = login;
}

In this way, the login would exist, because you would instantiate it and be able to access it the way you want.

Usuario entrada = new Usuario(new Login());
entrada.nome = TXTCadastroUsuarioNome.Text;
entrada.login.login = TXTCadastroUsuarioLogin.Text;
entrada.login.senha = TXTCadastroUsuarioSenha.Text;
    
29.11.2015 / 01:44