locked
Problem with Session objects RRS feed

  • Question

  • User-2006371901 posted

    I'm trying to set up a few session objects from input box text strings.

    [in code behind for a method that takes button click and sends data to dbase}

    string rFname = Request["Fname"];
    ...
    ...
    rFname = Session["sFname"].ToString();

    Error (with rFname = Session...) Object reference not set to an instance of an object

    have tried different combinations , still no luck

    TIA
    Ned



    Thursday, October 11, 2018 3:53 PM

All replies

  • User475983607 posted

    There is no indication in the code snippet that Session["sFname"] is ever assigned a value.   A common pattern when using Session is to always check if the Session value is null before trying to read the contents.  If Session is null then repopulate Session.

    string rFname;
    if(Session["sFname"] != null)
    {
    	rFname = Session["sFname"];
    }
    else
    {
    	//Populate Session
    }

    Thursday, October 11, 2018 4:29 PM
  • User1120430333 posted

    If you never put the object into session, then the object will not be there if you try to get the object for the session.

    Thursday, October 11, 2018 9:16 PM
  • User61956409 posted

    Hi Norkle,

    rFname = Session["sFname"].ToString();

    Error (with rFname = Session...) Object reference not set to an instance of an object

    If you do not set the Session with that key, it will return null. When you call ToString() on that null, you get the exception.

    To solve the exception, as others mentioned, please make sure you assigned value to session variable. Or check if that session variable is null in your code logic before you read it.

    With Regards,

    Fei Han

    Friday, October 12, 2018 2:38 AM