Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Passing information between pages -The .NET way

0.00/5 (No votes)
22 Sep 2004 1  
Article which demonstrates how to pass data between pages.

Introduction

For those ASP developers who are new to ASP.NET:

I am not going in detail about the Response.Redirect or Session variables because they both are the same like classic ASP. This article is for those developers who used POST method of Form in ASP to pass the Form variables from one page to another. Surprisingly, in ASP.NET, we cannot pass the Form variables from one page to another by posting or submitting the form using a submit button. I found out a little bit stranded at first. But soon I found out this new method of passing Form variables. (Who wants the old form submission now.)

The method of doing it

This is a bit complex but classy method of passing values across pages. Here, we expose the values we want to access in other pages as properties of the Page class. Here, we code extra properties that we want to access in another web form. However, the efforts are worth considering. This method is object oriented than earlier methods. The entire process works as follows:

  1. Create the web form with controls that carry values.
  2. Create property with Get procedures to return the values in the controls.
  3. Provide some button that posts the Form to another WebForm.
  4. In the button click event handler, call Server.Transfer method that will transfer execution to the specified WebForm.
  5. In the second Form, you can get a reference to the first Form instance by using ontext.Handler property and cast it to the source WebForm class.

Then, you will use the Get properties we created to access the control values.

Create a WebForm as shown below:

Sample screenshot

Write properties to access the values in the controls inside the source Page class:

public string Name
{
    get{return txtName.Text;}
} 
public string Email
{
    get{return txtEmail.Text;}
}
public string Phone
{
    get{return txtPhone.Text;}
}

On the button click event, write code:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
    Server.Transfer("destination.aspx");
}

On the Page_Load of the destination Page, write the following code to access the public properties:

SourcePage pgSource;
pgSource= (SourcePage) Context.Handler; 
Response.Write(pgSource.Name + "<br>");
Response.Write(pgSource.Email + "<br>");
Response.Write(pgSource.Phone + "<br>");

History

  • Version 1.0

    I thank Mr. Alvin George for writing this small code for me, due to my lack of time.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here