Test if Session Variable Exists!!

Discussion in 'ASP .Net' started by Adam J Knight, Feb 17, 2006.

  1. Hi all,

    I am trying to test to see if a Session variable exists.

    This was my initial attempt, and doesn't work
    int intInstructorID = (Session["InstructorID"].ToString() == null ?
    Convert.ToInt32(Request.QueryString["InstructorID"]):
    Convert.ToInt32(Session["InstructorID"]));


    Can anyone give me a head up on the best way to do this??

    Cheers,
    Adam
     
    Adam J Knight, Feb 17, 2006
    #1
    1. Advertisements

  2. Adam J Knight

    kahtava Guest

    You've got it..

    Perhaps avoid the use of the ternary operator for readability sake, but
    then again you may get better performance from short circuiting the
    ternary if statement.

    I would suggest sticking to either session variables or query strings;
    in the end it makes life easier.

    if( Session["InstructorID"] != null ){
    Convert.ToInt32(Request.QueryString["InstructorID"]):
    }
    else{
    Convert.ToInt32(Request.QueryString["InstructorID"]):
    }

    I found that through URL ReWriting I could get the functionality I
    desired with session variables through the use of query strings.

    Cheers,
    -Adam
     
    kahtava, Feb 17, 2006
    #2
    1. Advertisements

  3. Adam J Knight

    Hans Kesting Guest

    Hi all,
    The test 'Session["InstructorID"].ToString() == null' will fail
    if Session["InstructorID"] is null, because then there is nothing to
    call ToString() on. Remove the ToString and it should work (*if* you
    are sure that either the Session or the QueryString delivers something
    that can be converted into string).

    int intInstructorID = (Session["InstructorID"] == null ?
    Convert.ToInt32(Request.QueryString["InstructorID"]):
    Convert.ToInt32(Session["InstructorID"]));

    Hans Kesting
     
    Hans Kesting, Feb 17, 2006
    #3
  4. Perhaps:

    if( Session["InstructorID"] != null ){
    Convert.ToInt32(Session["InstructorID"]):
    }
    else{
    Convert.ToInt32(Request.QueryString["InstructorID"]):
    }
     
    Ravi Ambros Wallau, Feb 17, 2006
    #4
    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.