Variable Error Null in C # [duplicated]

1

Hi, I have the following code and when I run it I get the error that the variable facturaedit.Detallefacturas[i].IDDetalleFactura is Null.

code:

    public ActionResult Edit(int id)
    {   //Instanciamos el modelo (los modelos siempre estan vacios, simplemente el formato)         
        FacturaViewModels facturaedit = new FacturaViewModels();
        //Le decimos que la factura selecionada es la que es = al id
        facturaedit.Facturas = db.Facturas.FirstOrDefault(fac => fac.IDFactura == id);
        //No podemos convertir una lista de la bd en una lista del modelo de una entonces creamos una
        //variable que contenga esos registros de detalle de la factura
        var detalle = db.DetalleFacturas.Where(d => d.IDFactura == id).ToList();
        //Validar ID y existencia de Factura   sino redirigir al index         
        if (string.IsNullOrEmpty(Convert.ToString(id)) | facturaedit == null)
        {
            return RedirectToAction("Index");
        }
        //por cada detalle que este en la bd se le asigna al modelo un registro                      
        for (int i = 0; i < detalle.Count; i++)
        {
            facturaedit.Detallefacturas[i].IDDetalleFactura = detalle[i].IDDetalleFactura;
        }
        //al final le cargamos las listas que necesitamso para el editar la factura
        facturaedit.ListaEntidades = db.Entidades.ToList();
        facturaedit.ListaEstado = db.Estados.ToList();
        facturaedit.ListaFormasPago = db.FormasPagos.ToList();
        facturaedit.ListaNumeraciones = db.Numeraciones.ToList();
        facturaedit.ListaProductos = db.Productos.ToList();
        facturaedit.ListaIva = db.Iva.ToList();

        return View(facturaedit);
    }
    
asked by Jhon Castrillon 20.06.2017 в 20:07
source

3 answers

3

The problem occurs in this line

facturaedit.Detallefacturas[i].IDDetalleFactura = detalle[i].IDDetalleFactura;

the problem is that

facturaedit.Detallefacturas[i] has a null value

When you create the instance of FacturaViewModels , ensure that you create the object array Detallefacturas

 FacturaViewModels facturaedit = new FacturaViewModels();
    
answered by 20.06.2017 в 21:01
0

Initialize the object before

facturaedit.Detallefacturas[i].IDDetalleFactura = new...

or make a copy of the object instead of an assignment

    
answered by 22.06.2017 в 17:02
0

I still needed to put it in the end that is an array

facturaedit.Detallefacturas = db.DetalleFacturas.Where(item => item.IDFactura == id).ToArray();

Thank you!

    
answered by 22.06.2017 в 22:24