Click here to Skip to main content
15,894,720 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
In my shopping cart project, I use 'Home.aspx' as start page. I use a variable 'v_MyCart' to store the number of products selected for display. To use this variable in all other pages I use a session called as 'Session["mycart"]. The timeout for this session is 20mts. In 'AddToCart.aspx' page the value is incremented by one whenever I click one 'AddToCart button' and is displayed accordingly. But, from 'AddToCart' page if I select 'Home' button the display at 'Home' page becomes zero. I understand that this happens because of line 'Session["mycart"]=v_MyCart;'. If I comment this line and run the project after a gap of 20 mts what happens is , an exception reflects:Object reference not set to an instance of an object.
How to rectify this error, that is, whenever I click the 'Home' button within 20mts of time frame, the value in v_MyCart should not become zero.


C#
public partial class Home : System.Web.UI.Page
{
    static int v_MyCart;

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["prasiddhiConnectionString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["mycart"] =  v_MyCart;
            v_MyCart = (int)Session["mycart"];
            LblMyCart.Text = Convert.ToString(v_MyCart);
            LblMyCart.Visible = true;
Posted

v_mart should not be static and should be a local variable inside page_load method

Make below change in Page_load

C#
int v_Mycart =0;
if (!IsPostBack)
   {
      if(Session["mycart"] !=  null)
        {
            v_MyCart = (int)Session["mycart"];
            
        }

        LblMyCart.Text = Convert.ToString(v_MyCart);
        LblMyCart.Visible = true;
   }
 
Share this answer
 
After 20 min you are getting object reference error because your session is getting expired. For Session["mycart"] session, instead of assigning session with value from variable v_MyCart variable, directly assign value to the session variable and everything will work smoothly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900