Mimanshu
Mimanshu

Reputation: 173

Object reference not set to an instance of an object when using a session object

Whats wrong in this?

strFname = this.Session["FileName"].ToString();

while i defined it as

Session["FileName"] = strFname;

Its giving object reference error.

Upvotes: 0

Views: 1358

Answers (2)

Lukas
Lukas

Reputation: 2923

There are ways you can keep sessions alive forever as long as you do not close the window. In the page you wish to keep sessions alive, add this to the .aspx page somewhere on the bottom, just before

<!-- Keep all session variables alive -->
<iframe id="Defib" src="Defibrillator.aspx" runat="server" frameborder="0" height="0" width="0"></iframe>

Now you'll have to make a new page. Call it Defibrillator.aspx This isn't my idea, but I forgot the author's name.

Defibrillator.aspx

<body></body>

Defibrillator.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    Response.AddHeader("Refresh", Convert.ToString((Session.Timeout * 60) - 10));
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062660

Session can be transient. It may well disappear, or you might be in a new session that has never assigned anything to that key. Assume the worst - in fact, all you need is:

strFname = (string)Session["FileName"];
if(strFname != null) {
    // ...
}

Upvotes: 3

Related Questions