Turning a boolean into session variable

Beep picture Beep · Nov 10, 2013 · Viewed 21k times · Source

Any ideas on how to turn "edible" in the code into a session to display as a label on a different page. Help will be much appreciated.

The label will display message like yes can eat

code bellow

public int totalCalories()
        {
            return grams * calsPerGram;
        }
        public string getFruitInfo()
        {
            string s;
            if (edible == true)
            {
                s = fName + " is good and it has " + totalCalories() +
 "calories";
            }
            else
            {
                s = "Hands off! Not edible";
                //edible = Sesion ["ediblesesion"] as bool;
                // Session ["ediblesession"] = edible;
            }
            return s;
        }
    }

Answer

Guffa picture Guffa · Nov 10, 2013

You already have the code for setting the session variable in the comment inside the if statement:

Session["ediblesession"] = edible;

However, you probably want to set the session variable outside the if statement, so that it gets a value even if the boolean value is true.

When you want to read the value back in the other page, you will get the boolean value boxed in an object, so you would need to cast it back to a boolean value:

edible = (bool)Session["ediblesession"];

Be careful with the spelling. If you try to read a session variable with the name "ediblesesion" (as in the code in your comment), you won't get the variable that you stored as "ediblesession", and the compiler can't tell you that you made a typo as it's not an identifier.

If you want to read the value, but might come to the page without having set the value first, you would need to check if it exists:

object value = Session["ediblesession"];
if (value != null) {
  edible = (bool)value;
} else {
  edible = false; // or whatever you want to do if there is no value
}