Session state from one page

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 3010 Views - Last Post: 09 October 2012 - 02:19 PM Rate Topic: -----

#1 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Session state from one page

Posted 07 October 2012 - 02:11 PM

Hi:

I can't seem to figure out why I can't display the session values I have stored in one other page. When I enter the name and birthday and click enter the name is supposed to be displayed on the next page, but for some reason it won't show up even though I'm pretty sure I have the code written correctly.

Code in page load event:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    

    protected void Page_Load(object sender, EventArgs e)
    {

        string name = (string)Session["NAME"];
        Session["NAME"] = name;
        //int year = (int)Session["YEAR"];
        Label1.Text = "" + Session["NAME"];

        int randomNum;
        btnNew.Visible = false;

        txtGuess.Focus();


        if (!IsPostBack)
        {
                Random number = new Random();

                randomNum = number.Next(1, 51);
                Session["number"] = randomNum;
                Session["Count"] = 0;
               // lblNum.Text = "" + randomNum;
            }
    }
    protected void btnGuess_Click(object sender, EventArgs e)
    {
        
            int random = (int)Session["number"];  
            int num;
            bool guess = Int32.TryParse(txtGuess.Text, out num);
           

            if (guess == false)
            {
                lblError.Text = "Invalid character. Must be a number";
            }

            if (guess == true)
            {
                if (num > 25 || num < 1)
                {
                    lblError.Text = "Number is not in range. Must be between 1 and 25.";
                }

                else if (num < 26 || num > 1)
                {
                   
                       int count = (int)Session["Count"];
                        count++;
                        Session["Count"] = count;
                    

                    if (num == random)
                    {
                        lblError.Text = "Correct guess! It took you " + Session["Count"] + " guesses";
                        txtGuess.ReadOnly = true;
                        btnNew.Visible = true;
                        btnGuess.Enabled = false;
                        btnGiveup.Enabled = false;

                    }

                    else if (num != random)
                    {
                        lblError.Text = "Incorrect guess. ";
                        if (num < random)
                        {
                            lblError.Text += "Guess higher";
                        }
                        else if (num > random)
                        {
                            lblError.Text += "Guess lower";
                        }
                    }
                }
            }
            
}
    protected void btnGiveup_Click(object sender, EventArgs e)
    {

        int random = (int)Session["number"];

        txtGuess.ReadOnly = true;
        btnNew.Visible = true;
        btnGuess.Enabled = false;
        btnGiveup.Enabled = false;

        lblError.Text = "Correct number was: " + random + ". Number of valid guesses made: " + Session["Count"];
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        int randomNum;
        Random number = new Random();

        randomNum = number.Next(1, 26);
        Session["number"] = randomNum;
        //lblNum.Text = "" + randomNum;

        Session["Count"] = 0;
        lblError.Text = "";
        txtGuess.ReadOnly = false;
        txtGuess.Text = "";
        btnNew.Visible = false;
        btnGuess.Enabled = true;
        btnGiveup.Enabled = true;
    }
}



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="welcome.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Welcome</title>
    <style type="text/css">
        .newStyle1
        {
            border-style: solid;
            border-width: 1px;
            padding: 1px 4px;
            font-family: Calibri;
            margin-right: 165px;
            width: 521px;
        }
        .style1
        {
            font-family: Calibri;
            font-weight: normal;
        }
    </style>
</head>
<body>
    <h2 class="style1">
        Welcome to the guessing game!</h2>
    <form id="form1" runat="server" defaultbutton="btnPlay">
    <div class="newStyle1">
    
        <br />
    
        <asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        &nbsp;
        <asp:RequiredFieldValidator ID="reqName" runat="server" ControlToValidate="txtName" ForeColor="Red"
            ErrorMessage="Name is required."></asp:RequiredFieldValidator>
        <br />
        <asp:Label ID="lblBirthDate" runat="server" Text="Date of birth:"></asp:Label>
    
    &nbsp;
        <asp:TextBox ID="txtBirth" runat="server"></asp:TextBox>
&nbsp;
        <asp:RequiredFieldValidator ID="reqBirth" runat="server" Display="Dynamic" ControlToValidate="txtBirth" ForeColor="Red"
            ErrorMessage="Date of birth is required."></asp:RequiredFieldValidator>
        <asp:CompareValidator ID="compAge" runat="server" ControlToValidate="txtBirth" Type="Date" Operator="LessThan" ForeColor="Red"
            ErrorMessage="Date invalid."></asp:CompareValidator>
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnPlay" runat="server" Text="Play" onclick="btnPlay_Click" PostBackUrl="~/guess_game.aspx" />
    
    </div>
    </form>
</body>
</html>



Code in button click event:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        compAge.ValueToCompare = DateTime.Now.ToString("d");

    }
    protected void btnPlay_Click(object sender, EventArgs e)
    {
        DateTime birthDate;

        if (DateTime.TryParse(txtBirth.Text, out birthDate))
        {
            int year = DateTime.Today.Year - Convert.ToDateTime(txtBirth.Text).Year;

            Session["YEAR"] = year;
        }
        Session["NAME"] = txtName.Text;
    }
}



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="guess_game.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CO884 Lab 1 - Adam Graham</title>
    <style type="text/css">
        .style1
        {
            height: 80px;
            width: 86px;
            z-index: 1;
            left: 228px;
            top: 70px;
            position: absolute;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server" defaultbutton="btnGuess">
    <div>
    
        <h1>
            Number Guessing Game</h1>
        <p>
            &nbsp;Guess a number between 1 and 25.<img 
                alt="" class="style1" src="Images/green-question-mark.jpg" /></p>
    
    </div>
    <asp:TextBox ID="txtGuess" runat="server" MaxLength="2" 
        ></asp:TextBox>
    <asp:Label ID="lblNum" runat="server"></asp:Label>
    &nbsp;&nbsp;
    <p>
        <asp:Button ID="btnGuess" runat="server" Text="Guess" 
            onclick="btnGuess_Click" />
        <asp:Button ID="btnGiveup" runat="server" Text="Give up" 
            onclick="btnGiveup_Click" />
        <asp:Button ID="btnNew" runat="server" Text="Start New Game" 
            onclick="btnNew_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    <asp:Label ID="lblError" runat="server"></asp:Label>
    <p>
        &nbsp;</p>
    </form>
</body>
</html>


This post has been edited by jaArch: 07 October 2012 - 04:33 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Session state from one page

#2 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 08 October 2012 - 06:27 AM

the reason nothing shows up is because Sessions are just objects. They do not know or care what is being stored within them so it is your job to tell it what is in them. You are also responsible for checking to make sure something is actually in there, because Session also does not care if there is anything stored within it.

EX:

Lets say I have an ID that I want to store in session
Session["ID"] = request.ID;



now on the next page I want to pull the ID back out of session. If I just use Session["ID"] it is going to give me back an object, so I need to tell it what that object is. In this case it is a string type:

string requestID = Session["ID"].ToString();



this will set requestID equal to what ever is stored in Session["ID"], but what happens when there is nothing stored in Session["ID"] either because I never set it or because the session expired? It will throw an error. To make this safe I need to make sure that it is not null first:

string requestID = "";
if(Session["ID"] != null)
{
    requestID = Session["ID"].ToString();
}



now i can use requestID safely knowing that I won't throw any errors.

This post has been edited by rgfirefly24: 08 October 2012 - 06:27 AM

Was This Post Helpful? 0
  • +
  • -

#3 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 06:35 AM

So basically I just need to ensure that it's not null first then put the session in a label to display?
Was This Post Helpful? 0
  • +
  • -

#4 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 08 October 2012 - 06:46 AM

yes, as long as you call .ToString() on it. You are not restricted to labels though, when you call .ToString() on it, you can use it anywhere a normal string can be used.

This post has been edited by rgfirefly24: 08 October 2012 - 06:47 AM

Was This Post Helpful? 0
  • +
  • -

#5 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 06:54 AM

Ok, because I have tried that and it still doesn't show the name I have entered in the textbox:

        string name = txtName.Text;
        Session["NAMES"] = name.ToString();


On the next page I have:

string name = "";
        if (Session["NAMES"] != null)
        {
            name = Session["NAMES"].ToString();
            lblError.Text = "" + Session["NAMES"];
        }

This post has been edited by jaArch: 08 October 2012 - 06:55 AM

Was This Post Helpful? 0
  • +
  • -

#6 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 08 October 2012 - 06:57 AM

Your issue is because your setting lblError.Text equal to Session["Names"] instead of name.

Change line 5 to this: lblError.Text = "" + name;

This post has been edited by rgfirefly24: 08 October 2012 - 06:58 AM

Was This Post Helpful? 0
  • +
  • -

#7 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 07:04 AM

This is really odd...I have tried changing it to + name instead but it still won't show the name I have entered in the textbox
Was This Post Helpful? 0
  • +
  • -

#8 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 08 October 2012 - 09:18 AM

have you tried debugging it to see what value is stored in your session?
Was This Post Helpful? 0
  • +
  • -

#9 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 10:04 AM

I'm not sure how I would do that - I only use the Web Developer debugging tool. So, no I haven't tried to debug it - it's odd because yesterday it was working and was showing the values in the sessions. When I ran it again it wouldn't show the session values.
Was This Post Helpful? 0
  • +
  • -

#10 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 08 October 2012 - 11:18 AM

are you using Visual Studio or Visual web developer? Either of those have the ability to debug your website by putting a breakpoint at the line you want to stop the execution at (hitting F9) and then hit F5 to run the program. Once it stops the execution you should be able to highlight the session variable and right-click -> Add Watch to see what's in it.
Was This Post Helpful? 0
  • +
  • -

#11 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 11:38 AM

I'm using Web Developer and I couldn't add watch so I just clicked pin to source and it says the variable is not set.
Was This Post Helpful? 0
  • +
  • -

#12 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 08 October 2012 - 05:43 PM

I did what you advised me to do, but when I did it the value came up as null instead of being the value of the textbox.

This post has been edited by jaArch: 08 October 2012 - 05:44 PM

Was This Post Helpful? 0
  • +
  • -

#13 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 09 October 2012 - 05:38 AM

show me your updated code
Was This Post Helpful? 0
  • +
  • -

#14 jaArch  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 217
  • Joined: 23-March 10

Re: Session state from one page

Posted 09 October 2012 - 07:39 AM


string name = "";
        if (Session["NAMES"] != null)
        {
            name = Session["NAMES"].ToString();
            lblError.Text = "" + Session["NAMES"];
       

This post has been edited by jaArch: 09 October 2012 - 07:40 AM

Was This Post Helpful? 0
  • +
  • -

#15 rgfirefly24  Icon User is online

  • D.I.C Lover
  • member icon


Reputation: 282
  • Posts: 1,491
  • Joined: 07-April 08

Re: Session state from one page

Posted 09 October 2012 - 07:45 AM

Your still trying to set lblError.Text equal to an object of unknown type. If you want to do it the way you have it you need to add .ToString() to the end of line 5.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2