5

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);
    }
  }

2 Answers 2

4

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>();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

When you create an new Order the filed OrderRow is null. You must initialize Order row on Order constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.