How to determine if a Session Variable exists?

Discussion in 'ASP .Net' started by Shapper, Jun 8, 2005.

  1. Shapper

    Shapper Guest

    Hello,

    How to determine if a Session Variable exists?

    In Page_Load I need to check is Session("MyVar") Exists.
    If it doesn't exist then I created it and give it a value:
    Session("myVar") = "Value"

    Thanks,
    Miguel
     
    Shapper, Jun 8, 2005
    #1
    1. Advertisements

  2. Shapper

    Ziemowit Guest

    If variable doesn't exist then its null. Simlpy.

    Ziemowit
     
    Ziemowit, Jun 8, 2005
    #2
    1. Advertisements

  3. Shapper

    Nawaz Ijaz Guest

    Simply do this..

    if ( Session("MyVar") == "" )
    {
    Session("MyVar") = "Your Value"
    }
     
    Nawaz Ijaz, Jun 8, 2005
    #3
  4. Ancient Zen problem:

    If a Session variable is set, and there is no class to read it, does it
    consume resources?

    --
    ;-)

    Kevin Spencer
    Microsoft MVP
    ..Net Developer
    Ambiguity has a certain quality to it.
     
    Kevin Spencer, Jun 8, 2005
    #4
  5. Shapper

    Joined:
    Sep 21, 2011
    Messages:
    2
    Likes Received:
    0
    session variable exists or not?

    Its difficult to check whether a session name exists or not..
    Because we cannot use a session instance name before it is being declared, means assigning the value to it. So it is better to use the following code. It is very bad programming. but if you want you can use it.

    try
    {
    string data = Session["sessionIds"].tostring();
    }
    catch(Exception ex)
    {
    // Do your handling code. ie, if you want to set the session value set here.
    }


    the idea behind is that using the session variable before declaring the value will thow an error. By this we can make sure that the session variable is not existing.
    If you want more specific just check what error throwing in this scenario and check whether the error is same as you required error and do the handling code.
    make sure to check whether the error is not coming from any other reasons.
    Usually the error will be "object reference not set to an instance of the object".
    Hope this will help some one..
     
    , Sep 21, 2011
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.