-1

I am using web forms, and the home page (Default.aspx) has login form. Now, if the user logs in, I want the page to reload and show the username (from database) in the text box and disable it. But I don't seems to be able to access the session variable to do that! Even though I can do that when redirecting to other pages.

This is the login button code:

protected void LoginBtn_Click(object sender, EventArgs e)
{
  commonMethod.DB_OpenConnection();
  var userEmail = login.Text;
  var userPass = password.Text;
  SqlCommand myCommand = new SqlCommand("SELECT MemberName, Email, Pass, Member_Type FROM Member", commonMethod.myConnection);
  SqlDataReader myReader = null; 
  myReader= myCommand.ExecuteReader();
  while(myReader.Read())
  {
  if ((String)myReader["Pass"] == userPass && (String)myReader["Email"]==userEmail)
      {
            submitMsg.Text = "success";
            Session["username"] = (String)myReader["MemberName"];
            Session["role"] = myReader["Member_Type"];
            Response.Redirect("Default.aspx");
            break;
      }
      else
      { 
        submitMsg.Text = "Failed";
      }
      }
         commonMethod.DB_CloseConnection();
      }

And this is how I am trying to access the session username in the same page.

    public string username;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] != null)
        {
            username = (String)Session["username"];
            login.Text = username;
            login.Enabled = false;
        }
        else {
            username = "example@gmail.com";
            login.Text = username;
        }

    }

Why can't I access the session variables after logging in !?

  • 1
    Is the SessionState enabled? – Saravana Kumar Jan 02 '15 at 13:04
  • Yes, and the stored variables can retrieved in all other pages except the one which contains the form (which I create the session variables in) – Shaher Jamal Eddin Jan 02 '15 at 13:07
  • Try Server.Transfer("Default.aspx"); instead of Response.Redirect("Default.aspx"); The difference http://stackoverflow.com/questions/6778870/difference-between-response-redirect-and-server-transfer – jyrkim Jan 02 '15 at 13:20
  • What exactly do you mean by 'Why can't I access the session variables after logging in'? Do you actually mean that they are simply returning null for Session["username"] etc? – sr28 Jan 02 '15 at 13:30

1 Answers1

0

Thank you guys for help, I actually found out what I am doing wrong: am setting login.Text = username; in the Page_Load method that is why every time the data passed by user in the 'login' text box is getting changed and then the if statement (that checks username and password) executes else { submitMsg.Text = "Failed"; } which causes the session variables to not be initialized.