Exforsys

Home arrow Technical Training arrow ASP.NET Training

Managing State with ASP.NET and C# Page - 3

Page 3 of 3
Author : Exforsys Inc.     Published on: 3rd May 2005    |   Last Updated on: 5th Nov 2010

Managing State with ASP.NET and C#

Using HttpContext to store the values

Ads

You can also use HttpContext to retrieve values from pages. The values are retrieved using properties or methods. It's a good idea to use properties since they are easier to code and modify. In your first page, make a property that returns the value of the TextBox.

public string GetName
{
get { return txtName.Text; }
}

We will use Server.Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. Simply add the following line of code in 'Server.Transfer' button click event:

Server.Transfer("WebForm5.aspx");

Now, let's go to the page where the values are being transferred, which in this case is "webForm5.aspx".

// You can declare this Globally or in any event you like
WebForm4 w;

// Gets the Page.Context which is Associated with this page
w = (WebForm4)Context.Handler;
// Assign the Label control with the property "GetName" which returns string
Label3.Text = w.GetName;

Using Application State to store the application level values

Sometimes, we need to access a value from anywhere in our page. For that, you can use Application variables. Here is a small code that shows how to do that. Once you created and assigned the Application variable, you can retrieve its value anywhere in your application.

// This sets the value of the Application Variable
Application["Name"] = txtName.Text;
Response.Redirect("WebForm5.aspx");

// This is how we retrieve the value of the Application Variable
if( Application["Name"] != null )
Label3.Text = Application["Name"].ToString();

Page Level State to Store the Session

Ads

This is one of the coolest feature of the Asp.net. Its called ViewState object. ViewState can store an object type which means it can store any type of class variables since they all are derived from the object class. ViewState can only be used if the page is posting back to itself. Here is a simple example of putting values on the view state:

ViewState["MyViewState"] = myVariable;



 
This tutorial is part of a ASP.NET Training tutorial series. Read it from the beginning and learn yourself.

ASP.NET Training

 

Comments