user1494459
user1494459

Reputation:

Session is set or not in ASP.NET

How to check that any of a Session is set or not in ASP.NET C# as we do in PHP

 if(session_id() == '')
 {
      // session has NOT been started
      session_start();
 }
 else
 {
      // session has been started
 }

And in ASP.Net C#

if (Session["userRole"].ToString() == "2")
       GridView3.Columns[7].Visible= true;   
else{
       GridView3.Columns[7].Visible= false;

The above code only checks the session named userRole. What is the alternate way of the above PHP code to C#?

Upvotes: 1

Views: 1552

Answers (3)

Mittchel
Mittchel

Reputation: 1926

In order to check if any session key is set try:

if(Session.Keys.Count > 0)
{
    Console.WriteLine("Session is filled");
}
else
{
    Console.WriteLine("Session is empty");
}

Every item is a 'key' in the Session object. So when the count equals zero, there are no session keys set. Is this what you wanted?

Upvotes: 2

Adil
Adil

Reputation: 148140

To check if the session key exists in Session collection you have to compare it with null

if (Session["userRole"] != null && Session["userRole"].ToString() == "2")

Edit based on comments, Session is property of Page class and will always exists and will not be null.

This property provides information about the current request's session. A Session object is maintained for each user that requests a page or document from an ASP.NET application. Variables stored in the Session object are not discarded when the user moves from page to page in the application; instead, these variables persist as long as the user is accessing pages in your application, MSDN.

Upvotes: 1

Ozan ÇAKİN
Ozan ÇAKİN

Reputation: 163

Another Solution use try catch

    try
    {
        if (Session["userRole"].ToString() == "2")
            GridView3.Columns[7].Visible = true;
        else
            GridView3.Columns[7].Visible = false;
    }
    catch (Exception)
    {
        GridView3.Columns[7].Visible = false;
    }

Upvotes: 0

Related Questions