How do I set a Session variable in a class

  • Thread starter Andrea Williams
  • Start date
A

Andrea Williams

I have created an additional class to handle some session handling for a new
web application, but I'm unable to set or retrieve the session variables.
Code is below.

The problem is, I get this error when trying to compile:
'System.Web.HttpContext.Session' denotes a 'property' where a 'method' was
expected
And it blue lines the word Session in my code. I've tried several different
ways to code this with no success.

If I can't set a session variable this way in a class, how is it done? I
saw that someone else was able to do it in a post in Dec, but that didn't
work for me.


I've done several searches and have come up with nothing that has helped.
In C# Please :)

Here are some things I've tried:
To return a session var:

HttpContext.Current.Session("MyVar").ToString()

System.Web.HttpContext.Current.Session("MyVar").ToString()

Session("MyVar").ToString()

Thanks in Advance for any help you might give me!

Andrea
 
K

Kevin Spencer

System.Web.HttpContext.Current.Session is the correct way to make the
reference. I don't know why you would have gotten an error when using this,
although I noticed that this was not the syntax used in the error message
you posted.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
C

Craig Deelsnyder

Andrea said:
HttpContext.Current.Session("MyVar").ToString()

System.Web.HttpContext.Current.Session("MyVar").ToString()

Session("MyVar").ToString()

Thanks in Advance for any help you might give me!

Andrea

C# uses brackets for indexes on arrays/collections, not parens (parens
are used to call methods). Change to:

HttpContext.Current.Session["MyVar"]
 
K

Ken Onweller \(.NET MCSD\)

in C#, Session is treated like an Array.

try: Session["MyVar"] instead of Session("MyVar")
 
I

Iain Wade

In c# the syntax is referencing an index of a collection or arrays is as
follows:

Session["MyVar"].ToString();

()'s are for method calls. Hence the exception.


-En
 
A

Andrea Williams

Duh! like Javascript! Although I didn't know THIS was treated like an
array and the only code samples I could find were in VB.... go figure!

THANKS to ALL of you!!
Andrea
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top