0

I'm trying to get the value from another page and to do this I'm using session. I have the variable equal to 5 if null (user never enters on other page), but for some reason, I get an error saying it is null.

So what is happening is the user will go to index.aspx in the browser and will enter their values. Since they didn't go to the other page then Session["StockSnickers"] will be null because they didn't fill in the textbox. Now, I want it to be set to 5. If the userSnickers is less than 5 then they will get redirected to another page where they will see it in table the data.

The issue I have is that it is saying it is null. How can I fix?

Error: enter image description here

Index.aspx

  protected void btnSubmit_Click(object sender, EventArgs e)
        {

        int userSnickers = int.Parse(txtAmountSnickers.Text);

        int stockSnickers = (int)Session["StockSnickers"];


        if (Session["StockSnickers"] == null)
        { 
            stockSnickers = 5;
        }

        if (stockSnickers < userSnickers)
        {
            lblSnickersError.Text = "Please enter a smaller value!";
        }
        else
        {
            if (Page.IsValid)
            {
                using (StoreContext context = new StoreContext())
                {
                    /*Validate*/
                    Order orders = new Order();
                    orders.Snickers = txtAmountSnickers.Text;
                    orders.Twix = txtAmountTwix.Text;
                    orders.Milkyway = txtAmountMilk.Text;
                    orders.KitKat = txtAmountKitKat.Text;
                    context.Order.Add(orders);
                    context.SaveChanges();
                    Response.Redirect("view_application.aspx");
                }
            }
        }

Inventory.aspx:

 public void someMethod() { 
        string snickersInventory = txtInventorySnickers.Text;
        int stockSnickers = Int32.Parse(snickersInventory);
        Session["StockSnicker"] = stockSnickers;
   }
Jay H
  • 3
  • 2

1 Answers1

0
int stockSnickers = (int)Session["StockSnickers"];


if (Session["StockSnickers"] == null)
{ 
    stockSnickers = 5;
}

The above code will throw an exception if StockSnickers does not exist in Session since you are trying to cast null to an int. The key is to reverse the logic so that can't occur:

int stockSnickers = 5;


if (Session["StockSnickers"] != null)
{ 
    stockSnickers = (int)Session["StockSnickers"];
}
mjwills
  • 23,389
  • 6
  • 40
  • 63
  • I changed this and it worked. The issue I run into now is if the user goes to the other page and sets it equal to 10, it is still equal to 5 – Jay H Jun 13 '19 at 01:01