0

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();
        }
ukhardy
  • 2,084
  • 1
  • 13
  • 12
Dhana
  • 1,618
  • 4
  • 23
  • 39

2 Answers2

2

There is absolutely no relation between your private field divWidthList and the public property DivWidthList. The public property is never initialized. You could initialize it for example in the constructor of the class:

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

or don't use an auto property:

public class AboutMod
{
    private List<int> divWidthList = new List<int>();
    public List<int> DivWidthList 
    {
        get
        {
            return divWidthList;
        }
        set
        {
            divWidthList = value;
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

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 
    }
ukhardy
  • 2,084
  • 1
  • 13
  • 12