How to store and retrieve multiple values in a single Session in ASP.Net

Last Reply on Oct 06, 2016 09:46 AM By dharmendr

Posted on Oct 06, 2016 02:13 AM

plz help me with the code and solution

<asp:TextBox ID="txtUname" runat="server" placeholder="UserName" class="textStyle"></asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server" placeholder="Password" class="textStyle"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" onclick="ValidateUser" />    
<asp:Label ID="lblmsg" runat="server" Text="Label"></asp:Label> 


protected void ValidateUser(object sender, EventArgs e)
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
        using (SqlCommand cmd = new SqlCommand("Validate_User"))
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", txtUname.Text.Trim());
            cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
            cmd.Connection = con;
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            userId = Convert.ToInt32(cmd.ExecuteScalar());
            if (dt.Rows.Count > 0)
                Session["uid"] = dt.Columns[0].ToString();
                Session["Username"] = dt.Columns[1].ToString();
                Session["city"] = dt.Columns[2].ToString();
                lblmsg.Text = "You're username and word is incorrect";
                lblmsg.ForeColor = System.Drawing.Color.Red;

        switch (userId)
            case -1:
                lblmsg.Text = "Username and/or password is incorrect.";
            case -2:
                lblmsg.Text = "Account has not been activated.";
                //FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
This is my stored Procedure..validated user

ALTER  PROCEDURE [dbo].[Validate_User]
    @Username NVARCHAR(20),
    @Password NVARCHAR(20)
    DECLARE @UserId INT, @LastLoginDate DATETIME
    SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
    FROM Users WHERE Username = @Username AND [Password] = @Password
    IF @UserId IS NOT NULL
        IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
            UPDATE Users
            SET LastLoginDate =  GETDATE()
            WHERE UserId = @UserId
            SELECT @UserId [UserId] -- User Valid
            SELECT -2 -- User not activated.
        SELECT -1 -- User invalid.


Posted on Oct 06, 2016 02:40 AM

Hi safal,

Refer the below code.

// After login store the details in hashtable and then pass the hashtable to session.
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("UId", "123");
ht.Add("UserName", "Test Name");
ht.Add("City", "Test City");
Session["EmployeeInfo"] = ht;

// You can retrive the value from session in your application.
if (Session["EmployeeInfo"] != null)
    System.Collections.Hashtable userDetails = (System.Collections.Hashtable)Session["EmployeeInfo"];
    string userId = userDetails.ContainsKey("UId") ? Convert.ToString(userDetails["UId"]) : string.Empty;
    string userName = userDetails.ContainsKey("UserName") ? Convert.ToString(userDetails["UserName"]) : string.Empty;
    string city = userDetails.ContainsKey("City") ? Convert.ToString(userDetails["City"]) : string.Empty;

Or you can make a class for that and store the value in it and pass the class object to the session.

// After login store the details in class object and then pass the object to session.
EmployeeInfo ei = new EmployeeInfo();
ei.Id = "123";
ei.Name = "Test Name";
ei.City = "Test City";
Session["EmployeeInfo"] = ei;

// You can retrive the value from session in your application.
if (Session["EmployeeInfo"] != null)
    EmployeeInfo eiDetails = (EmployeeInfo)Session["EmployeeInfo"];
    string userId = !string.IsNullOrEmpty(eiDetails.Id) ? eiDetails.Id : string.Empty;
    string userName = !string.IsNullOrEmpty(eiDetails.Name) ? eiDetails.Name : string.Empty;
    string city = !string.IsNullOrEmpty(eiDetails.City) ? eiDetails.City : string.Empty;

public class EmployeeInfo
    public string Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }

If in case of there would be possibility of increase the property then i would suggest you go with the 2nd option i.e. creating class object.

Posted on Oct 06, 2016 03:07 AM

Thank you sir for your guidance..

But still  i have some doubt

As i am only passing only two values username and password for login  by using stored procedure.

by comparing this values in userTable.. 

now i wan't to retrieve uid, username, password, city, email from usertable ..

and store this values in session varibales to display on other pages.

Is there any changes i have to make in my SP query or sql statement.

or there is something wrong in c# code..

please suggest changes


Posted on Oct 06, 2016 09:46 AM

You can't ask multiple queries within a question. This is against forum rules and necessary to maintain clean forum.
It is requested Mark Answer the replies when question is answered and ask a new question as a responsible member to help fellow programmers around the world.
Note: If you don't mark answers, people will loose interest in your questions.