|
Page 3 of 3
Using HttpContext to store the values
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
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;
Trackback(0)

|