Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I develop a web application in ASP.NET with C# behind code.Unfortunately I have faced into a problem for which I have no answer why this is happening.My main scope is to use a variable which every procedure can see not only as a declared variable but its value also. Say we have the following pseudo-code at c# side:
int variable; //say the variable is an integer one
procedure which happened clicking the button A
{
variable=4; //we give a value to our variable
}
procedure which happened clicking the button B
{
set the text of a label of the web-form giving it the value of "variable" //like saying Label1.Text=variable.ToString();
}So,first we click button A and then button B.We should wait to take the value of 4 written on the Label.Unfortunately this never happens.The "variable" loses its value passing from one procedure to another.In other words the variable cannot maintain its value.It is like using different variables although they have the same name. Somebody could say that I should declare the variable as a public static one. When we do this the problem is that every user of the web-form at the same time see the same value of the variable.This is not efective if I want the variable to get its value from a textbox with a user input (when at the procedure A we have the code "variable=TextBox1.Text").
A solution of using Session variables is not a proper one in case I want to use an array which values I want to use in more than one procedure.
So, does anyone know how I could give an end to my problem?Thanks a priori...and sorry for my English!

Both procedure A and procedure B access the same variable, but variables don't automatically maintain state across page calls in ASP.NET (lamentably, but for good reasons.)
You can remedy this a variety of ways...You can use the session, as you have already considered. The problem you mentioned with the session isn't an issue, since .NET will automatically serialize and deserialize arrays (or any other serializeable object) into the session so they work just like regular variables. Of course, for large objects you should remember to set them to nothing before leaving the page so they don't take up memory on your server.
You can also use the more traditional methods of using hidden fields and querystrings to maintain state (which really is all the viewstate is.)
Another option that fits particularly nicely if the variable is global to the application, and not specific to each user, is the IIS cache. .NET makes it pretty easy to work with.
Cache DocumentationRemember that the page load event handler fires before any of the button event handlers, so you can initialize whatever you need from the session, hidden fields, query string, or cache in there.
Good luck,
-SN

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |