Can a session variable be an int
? I want to increment Session["PagesViewed"]+1;
every time a page is loaded. I'm getting errors when trying to increment the session variable.
if (Session["PagesViewed"].ToString() == "2")
{
Session["PagesViewed"] = 0;
}
else
{
Session["PagesViewed"]++;
}
You need to test to see if the Session
variable exists before you can use it and assign to it.
You can do increment as follows.
Session["PagesViewed"] = ((int) Session["PagesViewed"]) + 1;
But, if the Session["PagesViewed"]
does not exist, this will cause errors. A quick null
test before the increment should sort it out.
if (Session["PagesViewed"] != null)
Session["PagesViewed"] = ((int)Session["PagesViewed"]) + 1;
Session["PagesViewed"]
will only return an Object - which is why your .ToString()
call works. You will need to cast this back to an int, increment it there, then put it back in the session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With