Reputation: 1924
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);
}
}
Upvotes: 5
Views: 169
Reputation: 34907
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>();
}
}
Upvotes: 4
Reputation: 370
When you create an new Order the filed OrderRow is null. You must initialize Order row on Order constructor.
Upvotes: 2