Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

asked on

Display text if Session is empty

Hello Experts,

I'm creating an application and I need help with hiding a Label Control if a particular Session variable does not exist or is empty. When a user logs into my system it stores there First, Last names, and EmpID which is there empoyee ID.

If a user signs in then I have there name displayed to a Label Control with a LinkButton allowing them to log out.

However, I need to display "Hello, Guest" if a user has not logged in and I then need to also disable or hide the LinkButton control.

Below is my current Page_Load code that displays the usersname First, Last names and EmpID to a Label Control if they have logged in.


Page_Load CodeBehind:

    protected void Page_Load(object sender, EventArgs e)
    {
        EmployeeLoginInfo();

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);


        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
    }


protected void EmployeeLoginInfo()
    {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }



HTML Markup:

<li class="rgt"><asp:Label ID="lblFullNameSession" runat="server" CssClass="rgtlabel"></asp:Label>&nbsp;&nbsp;<asp:LinkButton ID="lb_logout" OnClick="lb_logout_Click" runat="server">logout</asp:LinkButton></li>
Avatar of Jesus Rodriguez
Jesus Rodriguez
Flag of United States of America image

I'm not to savy on C# but must be something like that


EmployeeLoginInfo();

   
'Here check if the sessions variable are empty first
 if (Session["fname"] != null)  {
     lblFullNameSession.Text="Hello, Guest";
     lb_logout.visible=false;
  } else {
        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        lb_logout.visible=True;
    }
Hi,

try the following in the page load

if (Session["fname"] == null)  {
     lblFullNameSession.Text="Hello, Guest";
     lb_logout.visible=false;
  } else if(Session["fname"].ToString() == ""
{
     lblFullNameSession.Text="Hello, Guest";
     lb_logout.visible=false;
}
else
{
        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        lb_logout.visible=True;
    }
Avatar of Brian

ASKER

@k-designers and rajeeshmc,

First of all thank you very much for replying and helping out. Late last night I was able to take k-designers code modify it and got the following below. But after seeing your post rajeeshmca I had to ask myself if I was handling this the wrong way. Either your way or my way work fine in C# after I cleaned up the code a little bit. So my question is which way is better see both example below and let me know which one is the better of the two. As you will both see below I'm actually loading in the Session values before I even check to see whether or not that value is !null. Not sure if this is good practice or not.

My Code:

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        if (Session["empid"] != null)
        {
            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
        else
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }

Both of your code snippets:

        if (Session["empid"] == null)  
        {
            lblFullNameSession.Text="Hello, Guest";
            lb_logout.Visible = false;
        }
        else if (Session["empid"].ToString() == "")
        {
            lblFullNameSession.Text="Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
ASKER CERTIFIED SOLUTION
Avatar of Jesus Rodriguez
Jesus Rodriguez
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

@k-designers,

Which one would you use?
Second One. On that one you check iif is null or if is Empty. The only that I do on the last piece of code was join the two conditions in one line (I think that | works  like and or on VB)
Avatar of Brian

ASKER

Hi k-designers,

Ok, I will use your second one. But I ran into a bigger issue. When I logout it should kill my session(s) but when I navigate to another page it keeps the session value. How can I properly kill my session(s) across my entire application when I click on the logout button. Please see the code I'm using below for logging out. I have the same code on every page of my application.

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("application/index.aspx");
    }
I think that you have the property Session.RemoveAll() that kill and erase every variables stored on Sessions.

you only has to do this code on the logout_click event
 protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Session.Abandon();
        Response.Redirect("application/index.aspx");
    }


Also you must check on every page something like this when the page load

if (Session["empid"] == null) | (Session["empid"].ToString() == "")
        {
      Response.Redirect("application/index.aspx");
    }

to prevent that the guest enter to other pages
Avatar of Brian

ASKER

Hi k-designers,

Ok, first of all can you please post what you just posted on the link below. I created another post and if it works I would like to award you the points.

https://www.experts-exchange.com/questions/27840081/How-to-destroy-Session-data.html
Avatar of Brian

ASKER

Hi k-designers,

Also, I need to be able to allow users to access the Home, Information, and Contact pages without logging in. But if they login they I would like to display there login information with the ability to logout. But when they log out I don't want to see their session values.
Avatar of Brian

ASKER

Thank you!