Saturday, March 24, 2012

Passing (and retrieving) an ArrayList from a Session Var.

I am attempting to pass an ArrayList of objects to a Session Variable for retrieval on another page. Unfortunately, whenever I PostBack the page I get the following error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 49: objCart.SKU="111"
Line 50: objCart.Quantity=intQuantity
Line 51: aryCart.Add(objCart)
Line 52:
Line 53: Session("Cart")=aryCart

I have the Session("Cart") loading in a 'Not IsPostBack' conditional statement in the PageLoad and it works fine. But as soon as I try loading Session("Cart") into any PostBack situation (either in the PageLoad or any other function) I get the error above. I'm not sure why Session("Cart") only works for 'NotIsPostBack' situations. Is this just a problem related to ArrayLists? Any help would be greatly appreciated.are you creating a NEW objCart and/or a NEW aryCart?
Yes.
To anyone who is reading this thread, I've figured out the solution to this problem. When writing data to a Session variable from an ArrayList or an Array for the first time, the Session must first be initialized, otherwise it returns a Null value and you get the error I was getting. I solved this by using the IsNewSession method witihin a conditional statement to check if the Session was new or not. If it's new you cannot read from the Session variable, you may only write to it. If it's not new you can read from it or write to it.

0 comments:

Post a Comment