Estou tendo este erro quando no meu programa temos duas classes com métodos referenciados.
System.NullReferenceException was unhandled HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=Programacao em Linguagens Comerciais StackTrace: at Programacao_em_Linguagens_Comerciais.FormCadastroUsuario.button1_Click(Object sender, EventArgs e) in d:\users\lucas\documents\visual studio 2015\Projects\Programacao em Linguagens Comerciais\Programacao em Linguagens Comerciais\Tela_Cadastro_Usuario.cs:line 63 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) 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 Programacao_em_Linguagens_Comerciais.Program.Main() in d:\users\lucas\documents\visual studio 2015\Projects\Programacao em Linguagens Comerciais\Programacao em Linguagens Comerciais\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:
O erro ocorre quando estou tentando gravar no banco de dados o campo Usuario.login.login, ele passa pela parte que grava Usuario.nome e quando chega no que seria Usuario.login.login ele da este erro, saberiam me dizer o que estou fazendo de errado ?O código é auto incrementado no banco de dados.
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;
}
A parte que tem o erro, nela eu faço a verificação com o IF para ver se algum dos campos não esta em branco. Não sei porquê ela continua retornando essa mensagem de erro se nunca vai acontecer o if
se algum dos campos estiver vazio.
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
{
}
}
}
}