Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing a nullreference exception in this code?

Tags:

c#

asp.net

I try to add a new "Order" to my Session. I begin create a session in my Global.aspx file under Session_Start:

Session.Add("Cart", new WebShopData.Order());

At my login page i make a new Session:

 Session["userID"] = "User";
        ((Order)Session["Cart"]).UserID = userID;

Then at my shop page i want to add stuff to the session:

 if ((Order)Session["Cart"] != null)
((Order)Session["Cart"]).OrderRow.Add(new OrderRows({ArticleID = 2, Quantity = 1) });

At this last line i get att nullreference exception. Why could that be?


Here are my two classes:

   public class Order
   {
    public List<OrderRows> OrderRow { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
    public int UserID { get; set; }
   }

  public class OrderRows
  {
    public int ArticleID { get; set; }
    public int Quantity { get; set; }

    public override string ToString()
    {
            return string.Format("Artikel: {0}, Antal: {1}.\n", ArticleID, Quantity);
    }
  }
like image 510
daniel_aren Avatar asked Apr 23 '12 18:04

daniel_aren


1 Answers

You need to create an instance of OrderRow before using it. I suggest doing it in the constructor like so...

Add this to your Order class

public class Order {
     ....other stuff...

    public Order() {
      OrderRow = new List<OrderRows>();
    }
}
like image 163
JohnFx Avatar answered Nov 15 '22 04:11

JohnFx