user1525474 user1525474 - 1 year ago 65
ASP.NET (C#) Question

Send data from one page to another

I am trying to send form data from one page to another using C# ASP.Net. I have two pages default.aspx and default2.aspx.Here is the code I have in default.aspx:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Go"
PostBackUrl="~/Default2.aspx" />
<br />

From what I know so far the PostBackUrl is used to set the page in which you want the data to be sent is this correct?

Also how can I retrieve the data that is sent to Default2.aspx?

Answer Source

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.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download