Foros del Web » Programación para mayores de 30 ;) » .NET »

Error ABM C# "Referencia al objeto no establecida como instancia de un objeto"

Estas en el tema de Error ABM C# "Referencia al objeto no establecida como instancia de un objeto" en el foro de .NET en Foros del Web. Hola Gente, me presento. Soy Gonzalo, nuevo por aquí me registré debido a que tengo un problema y no se como solucionarlo. Llegué a la ...
  #1 (permalink)  
Antiguo 09/03/2011, 22:45
Avatar de GzaPro  
Fecha de Ingreso: marzo-2011
Ubicación: San Nicolas de los Arroyos
Mensajes: 5
Antigüedad: 13 años, 1 mes
Puntos: 0
Error ABM C# "Referencia al objeto no establecida como instancia de un objeto"

Hola Gente, me presento. Soy Gonzalo, nuevo por aquí me registré debido a que tengo un problema y no se como solucionarlo. Llegué a la conclusión de que estoy viviendo en un mundo paralelo al real donde nada tiene solución.

En fin llendo al grano, estoy haciendo un ABM con un punto de venta. Esta todo perfecto hasta el momento en que trato de guardar un Cliente en la base de datos.

Lenguaje: C#.NET
Base de datos: SQL

Este es el código de mi clase Cientes:

Código C:
Ver original
  1. namespace abm
  2. {
  3.     class clientes
  4.     {
  5.         public void AgregarCliente(string xnombre, string xapellido, string xcuit, string xdireccion, int xid_localidad, string xtelefono, string xcelular, string xemail, DateTime xfecha)
  6.         {
  7.             /*METODO AGREGAR CLIENTE*/
  8.             conexion cnn = new conexion();
  9.             SqlConnection cn = new SqlConnection(cnn.LeerConexion());
  10.             SqlCommand cmd = new SqlCommand("sp_insertarcliente", cn);
  11.             cmd.CommandType = CommandType.StoredProcedure;
  12.             cmd.Parameters.AddWithValue("@nombre",xnombre);
  13.             cmd.Parameters.AddWithValue("@apellido",xapellido);
  14.             cmd.Parameters.AddWithValue("@cuit",xcuit);
  15.             cmd.Parameters.AddWithValue("@direccion",xdireccion);
  16.             cmd.Parameters.AddWithValue("@id_localidad",xid_localidad);
  17.             cmd.Parameters.AddWithValue("@telefono",xtelefono);
  18.             cmd.Parameters.AddWithValue("@celular",xcelular);
  19.             cmd.Parameters.AddWithValue("@email",xemail);
  20.             cmd.Parameters.AddWithValue("@fecha",xfecha);
  21.             try
  22.             {
  23.                 cn.Open();
  24.                 cmd.ExecuteNonQuery();
  25.             }
  26.             catch (Exception ex)
  27.             {
  28.                 throw new Exception(ex.Message);
  29.             }
  30.             finally
  31.             {
  32.                 cn.Dispose();
  33.                 cmd.Dispose();
  34.             }
  35.         }
  36.  
  37.         /*METODO MODIFICAR CLIENTE*/
  38.         public void ModificarCliente(int xid_cliente, string xnombre, string xapellido, string xcuit, string xdireccion, int xid_localidad, string xtelefono, string xcelular, string xemail, DateTime xfecha)
  39.         {
  40.             conexion cnn = new conexion();
  41.             SqlConnection cn = new SqlConnection(cnn.LeerConexion());
  42.             SqlCommand cmd = new SqlCommand("sp_modificarcliente", cn);
  43.             cmd.CommandType = CommandType.StoredProcedure;
  44.             cmd.Parameters.AddWithValue("@id_cliente", xid_cliente);
  45.             cmd.Parameters.AddWithValue("@nombre", xnombre);
  46.             cmd.Parameters.AddWithValue("@apellido", xapellido);
  47.             cmd.Parameters.AddWithValue("@cuit", xcuit);
  48.             cmd.Parameters.AddWithValue("@direccion", xdireccion);
  49.             cmd.Parameters.AddWithValue("@id_localidad", xid_localidad);
  50.             cmd.Parameters.AddWithValue("@telefono", xtelefono);
  51.             cmd.Parameters.AddWithValue("@celular", xcelular);
  52.             cmd.Parameters.AddWithValue("@email", xemail);
  53.             cmd.Parameters.AddWithValue("@fecha", xfecha);
  54.             try
  55.             {
  56.                 cn.Open();
  57.                 cmd.ExecuteNonQuery();
  58.             }
  59.             catch (Exception ex)
  60.             {
  61.                 throw new Exception(ex.Message);
  62.             }
  63.             finally
  64.             {
  65.                 cn.Dispose();
  66.                 cmd.Dispose();
  67.             }
  68.         }
  69.         public void EliminarCliente(int xid_cliente)
  70.         {
  71.             conexion cnn = new conexion();
  72.             SqlConnection cn = new SqlConnection(cnn.LeerConexion());
  73.             SqlCommand cmd = new SqlCommand("sp_eliminarcliente", cn);
  74.             cmd.CommandType = CommandType.StoredProcedure;
  75.             cmd.Parameters.AddWithValue("@id_cliente", xid_cliente);
  76.             try
  77.             {
  78.                 cn.Open();
  79.                 cmd.ExecuteNonQuery();
  80.             }
  81.             catch (Exception ex)
  82.             {
  83.                 throw new Exception(ex.Message);
  84.             }
  85.             finally
  86.             {
  87.                 cn.Dispose();
  88.                 cmd.Dispose();
  89.             }
  90.         }
  91.  
  92.         public DataTable ListarCliente()
  93.         {
  94.             conexion cnn = new conexion();
  95.             SqlConnection cn = new SqlConnection(cnn.LeerConexion());
  96.             SqlCommand cmd = new SqlCommand("sp_listarcliente", cn);
  97.             cmd.CommandType = CommandType.StoredProcedure;
  98.             try
  99.             {
  100.                 SqlDataAdapter da = new SqlDataAdapter(cmd);
  101.                 DataTable tb = new DataTable();
  102.                 da.Fill(tb);
  103.                 return (tb);
  104.             }
  105.             catch (Exception ex)
  106.             {
  107.                 throw new Exception(ex.Message);
  108.             }
  109.             finally
  110.             {
  111.                 cn.Dispose();
  112.                 cmd.Dispose();
  113.             }
  114.         }
  115.        
  116.                                
  117.        }
  118.     }
  #2 (permalink)  
Antiguo 09/03/2011, 22:46
Avatar de GzaPro  
Fecha de Ingreso: marzo-2011
Ubicación: San Nicolas de los Arroyos
Mensajes: 5
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

y este es el código del formulario Clientes:

Código C:
Ver original
  1. namespace abm
  2. {
  3.     public partial class frmCliente : Form
  4.     {
  5.         public frmCliente()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         /*VARIABLE PARA ID DE CLIENTE*/
  11.         string ID;
  12.  
  13.         /*VARIABLE QUE INDICA SI SE PULSA NUEVO O MODIFICAR*/
  14.         private int temp = 0;
  15.  
  16.         /*VARIABLE PARA LA FECHA ACTUAL*/
  17.         DateTime FechaActual = DateTime.Now;
  18.  
  19.         public void MostrarGrid()
  20.         {
  21.             clientes persona = new clientes();
  22.             dtgDetalle.DataSource = persona.ListarCliente();
  23.         }
  24.  
  25.         /*MÉTODO PARA MOSTRAR LA LOCALIDAD*/
  26.         public void MostrarLocalidad()
  27.         {
  28.             localidades milocalidad = new localidades();
  29.             cboLocalidad.DataSource = milocalidad.ListarLocalidades();
  30.             cboLocalidad.DisplayMember = "nombre_localidad";
  31.             cboLocalidad.ValueMember = "id_localidad";
  32.         }
  33.  
  34.        
  35.  
  36.         public void GuardarCliente()
  37.         {
  38.             if (txtNombre.Text.Trim().Length > 0)
  39.  
  40.             {
  41.                 clientes persona = new clientes();
  42.                
  43.                 if (temp == 0)
  44.                 {
  45.                     persona.AgregarCliente(txtNombre.Text, txtApellido.Text, txtCuil.Text, txtDireccion.Text, Convert.ToInt32(cboLocalidad.SelectedValue.ToString()), txtTelefono.Text, txtCelular.Text, txtEmail.Text, FechaActual);
  46.                 }
  47.                 else
  48.                 {
  49.                     persona.ModificarCliente(Convert.ToInt32(ID), txtNombre.Text, txtApellido.Text, txtCuil.Text, txtDireccion.Text, Convert.ToInt32(cboLocalidad.SelectedValue.ToString()), txtTelefono.Text, txtCelular.Text, txtEmail.Text, FechaActual);
  50.                 }
  51.             }
  52.         }
  53.  
  54.         private void btnNuevo_Click(object sender, EventArgs e)
  55.         {
  56.             temp = 0;
  57.  
  58.             //VALORES EN BLANCO//
  59.             txtNombre.Text = "";
  60.             txtApellido.Text = "";
  61.             txtCuil.Text = "";
  62.             txtDireccion.Text = "";
  63.             txtTelefono.Text = "";
  64.             txtCelular.Text = "";
  65.             txtEmail.Text = "";
  66.             cboLocalidad.Text = "";
  67.  
  68.             //CONTROLES//
  69.             txtNombre.ReadOnly = false;
  70.             txtApellido.ReadOnly = false;
  71.             txtDireccion.ReadOnly = false;
  72.             txtCuil.ReadOnly = false;
  73.             txtTelefono.ReadOnly = false;
  74.             txtCelular.ReadOnly = false;
  75.             txtEmail.ReadOnly = false;
  76.             cboLocalidad.Enabled = true;
  77.  
  78.             //BOTONES//
  79.             btnNuevo.Enabled = false;
  80.             btnGuardar.Enabled = true;
  81.             btnModificar.Enabled = false;
  82.             btnEliminar.Enabled = false;
  83.             btnListar.Enabled = false;
  84.             btnCancelar.Enabled = true;
  85.             btnAtras.Enabled = false;
  86.  
  87.             //GRID//
  88.             dtgDetalle.Enabled = false;
  89.  
  90.             //FOCO//
  91.             txtNombre.Focus();
  92.         }
  93.  
  94.         private void btnGuardar_Click(object sender, EventArgs e)
  95.         {
  96.             GuardarCliente();
  97.         }
  98.  
  99.         private void btnModificar_Click(object sender, EventArgs e)
  100.         {
  101.             if ((dtgDetalle.Rows.Count > 0) && (dtgDetalle.CurrentRow.Cells[0].Value != null))
  102.             {
  103.                 temp = 1;
  104.                 ID = dtgDetalle.CurrentRow.Cells[0].Value.ToString();
  105.                
  106.                 /*CONTROLES*/
  107.                 txtNombre.ReadOnly = false;
  108.                 txtApellido.ReadOnly = false;
  109.                 txtDireccion.ReadOnly = false;
  110.                 txtCuil.ReadOnly = false;
  111.                 txtTelefono.ReadOnly = false;
  112.                 txtCelular.ReadOnly = false;
  113.                 txtEmail.ReadOnly = false;
  114.                 cboLocalidad.Enabled = true;
  115.                
  116.                 /*BOTONES*/
  117.                 btnNuevo.Enabled = false;
  118.                 btnGuardar.Enabled = true;
  119.                 btnModificar.Enabled = false;
  120.                 btnCancelar.Enabled = true;
  121.                 btnEliminar.Enabled = false;
  122.                 btnListar.Enabled = false;
  123.                 btnAtras.Enabled = false;
  124.                
  125.                 /*GRID*/
  126.                 dtgDetalle.Enabled = false;
  127.  
  128.             }
  129.         }
  130.  
  131.         private void btnEliminar_Click(object sender, EventArgs e)
  132.         {
  133.              if ((dtgDetalle.Rows.Count > 0) && (dtgDetalle.CurrentRow.Cells[0].Value != null))
  134.             {
  135.                 DialogResult resultado = MessageBox.Show("¿Está seguro que desea eliminar?", "Eliminar", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  136.                 if (resultado == DialogResult.Yes)
  137.                 {
  138.                     ID = dtgDetalle.CurrentRow.Cells[0].Value.ToString();
  139.                     clientes persona = new clientes();
  140.                     persona.EliminarCliente(Convert.ToInt32(ID));
  141.                     MostrarGrid();
  142.                 }
  143.             }
  144.                 else
  145.                 {
  146.                 MessageBox.Show("No ha sellecionado ningún dato", "Eliminar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  147.                 }
  148.            
  149.         }
  150.  
  151.         private void btnCancelar_Click(object sender, EventArgs e)
  152.         {
  153.             /*VALORES EN BLANCO*/
  154.             txtNombre.Text = "";
  155.             txtApellido.Text = "";
  156.             txtCuil.Text = "";
  157.             txtDireccion.Text = "";
  158.             txtTelefono.Text = "";
  159.             txtCelular.Text = "";
  160.             txtEmail.Text = "";
  161.            
  162.             /*CONTROLES*/
  163.             txtNombre.ReadOnly = true;
  164.             txtApellido.ReadOnly = true;
  165.             txtCuil.ReadOnly = true;
  166.             txtDireccion.ReadOnly = true;
  167.             cboLocalidad.Enabled = false;
  168.             txtTelefono.ReadOnly = true;
  169.             txtCelular.ReadOnly = true;
  170.             txtEmail.ReadOnly = true;
  171.  
  172.             /*BOTONES*/
  173.             btnNuevo.Enabled = true;
  174.             btnGuardar.Enabled = false;
  175.             btnModificar.Enabled = false;
  176.             btnEliminar.Enabled = false;
  177.             btnCancelar.Enabled = false;
  178.             btnListar.Enabled = true;
  179.             btnAtras.Enabled = true;
  180.  
  181.             /*GRID*/
  182.             dtgDetalle.Enabled = true;
  183.             txtNombre.Focus();
  184.         }
  185.  
  186.         private void btnListar_Click(object sender, EventArgs e)
  187.         {
  188.             btnAtras.Enabled = true;
  189.             MostrarGrid();
  190.         }
  191.  
  192.         private void dtgDetalle_CellEnter(object sender, DataGridViewCellEventArgs e)
  193.         {
  194.             /*ORDENAMIENTO DE COLUMNAS*/
  195.             txtNombre.Text = dtgDetalle.CurrentRow.Cells[1].Value.ToString();
  196.             txtApellido.Text = dtgDetalle.CurrentRow.Cells[2].Value.ToString();
  197.             txtCuil.Text = dtgDetalle.CurrentRow.Cells[3].Value.ToString();
  198.             txtDireccion.Text = dtgDetalle.CurrentRow.Cells[4].Value.ToString();
  199.             cboLocalidad.Text = dtgDetalle.CurrentRow.Cells[5].Value.ToString();
  200.             txtTelefono.Text = dtgDetalle.CurrentRow.Cells[6].Value.ToString();
  201.             txtCelular.Text = dtgDetalle.CurrentRow.Cells[7].Value.ToString();
  202.             txtEmail.Text = dtgDetalle.CurrentRow.Cells[8].Value.ToString();
  203.  
  204.             /*ENCABEZADO DE COLUMNAS*/
  205.             dtgDetalle.Columns[0].HeaderText = "Código";
  206.             dtgDetalle.Columns[1].HeaderText = "Nombre";
  207.             dtgDetalle.Columns[2].HeaderText = "Apellido";
  208.             dtgDetalle.Columns[3].HeaderText = "Cuil";
  209.             dtgDetalle.Columns[4].HeaderText = "Dirección";
  210.             dtgDetalle.Columns[5].HeaderText = "Código Localidad";
  211.             dtgDetalle.Columns[6].HeaderText = "Teléfono";
  212.             dtgDetalle.Columns[7].HeaderText = "Celular";
  213.             dtgDetalle.Columns[8].HeaderText = "Email";
  214.             dtgDetalle.Columns[9].HeaderText = "Fecha registro";
  215.  
  216.             /*ESTADO DE BOTONES*/
  217.             btnModificar.Enabled = true;
  218.             btnEliminar.Enabled = true;
  219.         }
  220.  
  221.        
  222.        
  223.     }
  224. }

El problema viene a que cuando le doy a guardar me sale el error de "referencia a objeto no establecida como instancia de un objeto", "nullexception", y tampoco me trae los datos de la tabla localidades al cboLocalidades.

Porfavor necesito que me ayuden y me digan que es lo que pasa, sinceramente pienso que es una tontería, pero no encuentro que es!

Saludos a todos y gracias de ante mano.
  #3 (permalink)  
Antiguo 10/03/2011, 08:21
 
Fecha de Ingreso: mayo-2010
Mensajes: 49
Antigüedad: 13 años, 11 meses
Puntos: 1
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Has un paso a paso con el visual studio, y nos dices exactamente donde sale la excepcion
  #4 (permalink)  
Antiguo 10/03/2011, 08:51
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 10 meses
Puntos: 267
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Exactamente concuerdo con J0rg3M4r10 hazle un seguimiento y nos cuentas en la linea en que cae.
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #5 (permalink)  
Antiguo 10/03/2011, 11:33
Avatar de GzaPro  
Fecha de Ingreso: marzo-2011
Ubicación: San Nicolas de los Arroyos
Mensajes: 5
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Hola gente, perdon tienen razon.

El error me sale en esta parte, en la linea persona.AgregarCliente(txtNombre.Text,.....,FechaA ctual); me la marca toda de amarillo

Código C:
Ver original
  1. public void GuardarCliente()
  2.         {
  3.             if (txtNombre.Text.Trim().Length > 0)
  4.  
  5.             {
  6.                 clientes persona = new clientes();
  7.                
  8.                 if (temp == 0)
  9.                 {
  10.                     persona.AgregarCliente(txtNombre.Text, txtApellido.Text, txtCuil.Text, txtDireccion.Text, Convert.ToInt32(cboLocalidad.SelectedValue.ToString()), txtTelefono.Text, txtCelular.Text, txtEmail.Text, FechaActual);
  11.                 }
  12.                 else
  13.                 {
  14.                     persona.ModificarCliente(Convert.ToInt32(ID), txtNombre.Text, txtApellido.Text, txtCuil.Text, txtDireccion.Text, Convert.ToInt32(cboLocalidad.SelectedValue.ToString()), txtTelefono.Text, txtCelular.Text, txtEmail.Text, FechaActual);
  15.                 }
  16.             }
  17.         }

Gracias de ante mano.

Última edición por GzaPro; 10/03/2011 a las 11:42
  #6 (permalink)  
Antiguo 10/03/2011, 11:58
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 10 meses
Puntos: 267
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Mmmmm a simple vista no veo un error posible en tu codigo... has declarado los campos de tu tabla clientes todos como not null? es probable que estes pasando un valor vacio y no este por ello ingresandolo, sino es asi, conjuntamente tambien hazle seguimiento a tu clase cliente y nos cuentas. Saludos!
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #7 (permalink)  
Antiguo 10/03/2011, 15:09
Avatar de GzaPro  
Fecha de Ingreso: marzo-2011
Ubicación: San Nicolas de los Arroyos
Mensajes: 5
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Listo lo solucioné. Algo que sinceramente me dejó perplejo porque no había nada que estuviera mal.

SOLUCION:

Dentro de mi basde de datos tenía una tabla "localidades" con una ID que hacía referencia a la misma ID en la tabla "clientes".
En el formulario ABM de Clientes yo tenía un ComboBox que traía los datos de la tabla "localidades". El problema era que el ComboBox no se llenaba y yo tenía en la base de datos el cambo ID en "Not null" entonces al tratar de guardar un nuevo Cliente tiraba Exception Null.
Lo corregí quitando la tabla "localidades" y llenando el ComboBox de manera simple desde sus opciones.
En conclusión, fue raro...

Saludos a todos y gracias por las respuesta tan rápidas.
  #8 (permalink)  
Antiguo 10/03/2011, 15:11
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 10 meses
Puntos: 267
Respuesta: Error ABM C# "Referencia al objeto no establecida como instancia de un obj

Excelente GzaPro! cualquier problema no dudes en postearlo. Saludos !.
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net

Etiquetas: establecida, instancia, objeto, referencia
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:50.