3

I'm at my wits end. My code isn't keeping track of sessions in C#

I'm using a user control which should pick up the session data, but it doesn't.

Here's the user control:

[Serializable]
public partial class studentComments : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string currStud;
        if (Session["CS"] == null)
        {
            currStud = "50";
        }
        else
        {
            currStud = (string)Session["CS"];
        }

        lblHeader.Text = "Comments for Student " + currStud;

        //display(currStud);
    }
}

and here is the code in the initial aspx.cs page

try
{
    student temp = studList.Find(o => o.student_id == studID);

    Session["CS"] = "45";
    PnlComment.Visible = true;
}
catch (NullReferenceException nre)
{
    lblTest.Text = "Student does not exist!";
}

Obviously the user control is in the PnlComment control.

edit I'm actually having an object passed to the session but I changed it to a static string for testing purposes, hoping that would simplify things. Alas, the label keeps showing 50. Why isn't it showing 45?

Help?

Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
Moe45673
  • 854
  • 10
  • 20

2 Answers2

0

It isn't a very widely held opinion but I've always found ASP's session management rules to be a bit counter intuitive so I tend to avoid using them at all. In addition I just don't like using strings as identifiers throughout my program as it can lead to collisions and other sorts of run time bugs.

Stick with using cookies to save your own session identifier that lives in the database and have it serialize/deserialize to an object with properties and fields. It's much more resilient to refactoring and if something goes wrong it's a lot easier to debug.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
  • Thanks a lot for the help. I'm actually having an object passed to the session but I changed it to a static string for testing purposes, hoping that would simplify things. Alas, the label keeps showing 50. Why isn't it showing 45? – Moe45673 Dec 03 '12 at 03:42
  • Errr, I didn't mean the keyword "static" but more like "as opposed to dynamic" – Moe45673 Dec 03 '12 at 04:05
0

Your default.aspx.cs page_load event is firing after the user control page_load event, so while the session value might be "45" after the page is loaded, the header text value will show the old value of "50" because it was set before then.

Ryan Weir
  • 6,377
  • 5
  • 40
  • 60
  • Ooooh, that's an interesting theory. I still can't use local variables in my user control, though, so how do I carry through that data? – Moe45673 Dec 03 '12 at 03:52
  • Ok, fixed it by adding a Response.Redirect("this url"); reload the page and the session info sticks! Thanks, cookingwithrye, you got it! – Moe45673 Dec 04 '12 at 05:24