static variables vs. session variables in ASP.NET

G

Guest

Hi,

I'm new to .NET and have a question about the use of static variables vs.
session variables in a web form in C#.

Instead of using a session variable to hold a string to persist during
datagrid paging. Can I use a static variable? Also, if I use a static
variable is that variable shared by everyone that brings up the aspx page?
Ex, if 4 people are viewing the aspx page is an instance of the static
variable created for each of the 4 people? Or is there just one instance of
that static variable shared across the 4 users?

BTW, I am using the session variable/static string to hold the value of some
filter criteria based on what buttons are pressed by the user which would hit
the database with different sql statements.

Thank you.
 
K

Ken Kolda

There is only one copy of a static variable, so it is not an appropriate
place to put session-specific information.

Ken
 
B

Ben Lucas

A static variable will be shared across all instances of the aspx page,
meaning that it is the same variable for every request that is coming in. I
don't think this is what you want because if you have 2 users, then their
actions will affect the view provided to the other user.

If this is a single page, you might consider using ViewState. This would
allow you to set a value for each of the users. However, this value would
only be good for the ASPX page they are on and only during postbacks. If
they leave and come back, the value won't be there anymore.
 
K

Ken Kolda

Correct -- there is only ever one instance of a static member. That also
means that if you use static data you need to ensure the code that accesses
that data is thread-safe. The Session object is where you want to put your
session-specific data.

Ken
 
G

Guest

Ben and Ken

Thank you guys very much for your help. I was trying to find a work around
for using session variables because for some reason the filter criteria I was
using on the datagrid was causing exceptions during postback (with paging
enabled). So I was trying to dump using Session variables and going with
Static variables. Now I see that's not the route to go.

Eventually, I set the web.config file with cookieless="true" and now the
paging is working correctly with my filter criteria. I'm going to play with
ViewStates as I'm interested in maintaining the state in just this one aspx
page. In either case, the viewstate/session variable holds a small string.

Once again, thank you!!!
 

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