Search code examples
c#asp.net-mvc-2automatic-properties

Object reference not set to an instance of an object execep occur while add the value for list in MVC2


Object reference not set to an instance of an object Exception thrown..(Null referenceException was unhandled by user code)

Model:

public class AboutMod
{
    private List<int> divWidthList = new List<int>();
    public List<int> DivWidthList { get; set; }
}

Control page:

 public ActionResult About()
        {
            AboutMod Obj = new AboutMod();//model class name 
            for (int i = 20; i <= 100; i += 20)
            {
                Obj.DivWidthList.Add(10);//Run time Exception occurs here 
            }
                return View();
        }

Solution

  • initialise Obj.DivWidthList first before attempting to use it:

        AboutMod Obj = new AboutMod();//model class name 
    
        Obj.DivWidthList = new List<int>();
    
        for (int i = 20; i <= 100; i += 20)
        {            
            Obj.DivWidthList.Add(10);//Run time Exception occurs here 
        }