Send data from one page to another

You have a few options, consider

  1. Session state
  2. Query string

Session state

If you are going to send data between pages, you could consider the use of Session State.

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Best of all, it is easy!

Put data in (for example on default1.aspx)

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

Get it out (for example on default2.aspx)

string firstname = Session["FirstName"] // value of FirstNameTextBox.Text;
string lastname = Session["LastName"] // value of LastNameTextBox.Text; 

Query string

If you are sending small amounts of data (eg id=4), it may be more practical to use query string variables.

You should explore the use of the query string variables, e.g.

http://www.domain.com?param1=data1&param2=data2

You can then get the data out like

string param1 = Request.QueryString["param1"]; // value will be data1
string param2 = Request.QueryString["param2"]; // value will be data2

You can use something like How do you test your Request.QueryString[] variables? to get the data out.

If you are unfamiliar with querystring variables check out their wikipedia article


Session variables can be useful in this context.

Foe example suppose your textboxes contain login credentials, then save them in sessions so that you can later use them in any other page. Like this:

In Button_Click-

Session["name"]=TextBox1.Text;
Session["pwd"]= TextBox2.Text;

Instead of PostBackUrl="~/Default2.aspx" you can write the following-

//in button click
Server.Transfer("~/Default2.aspx");

In Default2.aspx page load:

string a= Session["name"].ToString();
string b= Session["pwd"].ToString();

Try this in the Page_Load of Default2.aspx.

 if (PreviousPage != null)
        {
            if (((TextBox)PreviousPage.FindControl("TextBox1")) != null)
            {
                string txtBox1 = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
                Response.Write(txtBox1);
            }
        }

And yes you are correct, the data from page 1 will be sent to page 2 if you use the PostBackUrl attribute.

MSDN link

Tags:

C#

Asp.Net