Cross page postback in ASP.net

This is a very simple article about the cross page post back in asp.net.
So for this project I have 2 pages, namely Default.aspx and Page2.aspx. My Default.aspx looks like below.

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %><!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“><html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title>
</head>
<body>
    <form id=”form1″ runat=”server” defaultbutton=”Button1″ defaultfocus=”TextBox1″>
    <div>
        <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox><br />
        <br />
        <asp:Button ID=”Button1″ runat=”server” PostBackUrl=”~/Page2.aspx” Text=”Go to Next Page” /> </div>
    </form>
</body>
</html>

As you can see it simply contains a Textbox and a Button.
My Page2.aspx is something like below.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Page2.aspx.cs” Inherits=”Page2″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Label ID=”Label1″ runat=”server” Text=”Label” Width=”414px”></asp:Label><br />
        <br />
        <a href=”Default.aspx” mce_href=”Default.aspx”>Default.aspx</a></div>
    </form>
</body>
</html>

In addition to that I put the following code into my Page2.aspx.cs page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Page2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            TextBox mytext = (TextBox)PreviousPage.FindControl(“TextBox1”);
            Label1.Text = String.Format(“Welcome to the ASP.NET world {0}”, mytext.Text);
        }
    }
}

So make sure that the ID of your textbox in Default.aspx page is “TextBox1” or else you can give any name provided that name should pass into the FindControl function.

Now simply run the appliation, and you’ll see your textbox entry in the Default.aspx page is displayed in the label of the Page2.aspx

Enjoy!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s