Indra
Indra

Reputation: 115

Object reference not set to an instance of an object

I am getting below error when i am trying do sorting. Object reference not set to an instance of an object.

public static string SortColumn    
{
  get
    {
      return HttpContext.Current.Session["SORT_COLUMN"].ToString();
    }
    set
    {
        HttpContext.Current.Session["SORT_COLUMN"] = value;
    }
}

please help me on this...

Upvotes: 3

Views: 2609

Answers (2)

slfan
slfan

Reputation: 9129

You have to initialize the Session variable before you access the getter. Otherwise you have to check:

return HttpContext.Current.Session["SORT_COLUMN"] != null ? 
       HttpContext.Current.Session["SORT_COLUMN"].ToString() : string.Empty

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

Session["SORT_COLUMN"] can return null and you can't call something on nothing, so ToString would fail.

Also, HttpContext.Current could return null, meaning you can't access Session - this can happen if you're trying to access the context from the global.asax code.

Upvotes: 4

Related Questions