ASP.NET 2.0 – Accessing controls in the previous page

 

One of the problems faced by us in ASP.NET 1.x versions is the inability to transfer data between pages easily. Since ASP.NET 1.x pages postback to the same page by default, and you cannot do a post to another page (unless you remove the runat=”server” and other messy things), accessing the controls in the previous page becomes very difficult unlike classic ASP where you have a action tag to specify the new page and you can use the Request.Form to access the previous page values.

There is a more effective way of accessing the Controls in the previous page in ASP.NET 2.0. Its using the PreviousPage property of the Page.

Say we have a page Default.aspx with a Textbox “Text1” and a Button “Button1”.

We can access the controls in Default.aspx from another page by the following steps:-

1. Setting the PostBackUrl property of the Button to the New Page, as follows:-

<asp:Button ID=”button1″ Runat=server Text=”submit” PostBackUrl=”~/NewPage.aspx” />

2. Then, in the NewPage.aspx.cs, you can access the TextBox control on Default.aspx as follows:-

public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl(“Text1”);
Response.Write(tb.Text);}
}

Note that a new TextBox tb is declared and typecasted using the PreviousPage and FindControl of the ID of the Control in the Previous Page.  However, to retain the value across postbacks within the new page, its better to assign the text to a TextBox or Label in the NewPage.aspx such that its value is not lost across postbacks.  The reason behind is that, the PreviousPage becomes invalid once you postback in the same page.

We could still achieve this in ASP.NET 1.x versions by using the Server.Transfer but Server.Transfer has other undesirable effects like URL not updated in the browser and limitation within the application etc., 

Read More

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