ASP.NET 2.0 : Accessing controls in Previous Page

Hi,

In my earlier
article, I explained how the PostBackUrl property has made the job of posting the page to a different page easy in Whidbey.

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

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

There are two ways on how we can access the controls in Default.aspx from another page.

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" />

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


public void page_load()
{

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.

2. The other way is the old way of transferring the page to new page using Server.Transfer on the Click Event of the Button in the first page.

But in this case, the PostBackUrl property should not be specified for the Button control.

In the Button declaration in Default.aspx, the code should be

<asp:Button ID="button1" Runat=server Text="submit" OnClick="button1_Click" />

Then, in the codebehind,

void button1_Click(object sender, EventArgs e)
{
Server.Transfer("NewPage.aspx");
}

Still the PreviousPage.FindControl method would work.

This is a wonderful way of accessing the Controls in the Previous Page and I reckon it would be very useful for Developers.

Thanks.

Print | posted on Monday, April 25, 2005 8:01 AM

Comments on this post

# re: Whidbey: Accessing controls in Previous Page

Requesting Gravatar...
Thanks.. this is a great tip. But would be more useful if you could line up the pro and cons of this method as opposed to Request.Redirect etc..
Left by Rosdi on Mar 01, 2006 10:17 AM

# re: ASP.NET 2.0 : Accessing controls in Previous Page

Requesting Gravatar...
hanks.. this is a great tip. But would be more useful if you could line up the pro and cons of this method as opposed to Request.Redirect
Left by şişme bebek on Nov 20, 2008 1:16 PM

# re: ASP.NET 2.0 : Accessing controls in Previous Page

Requesting Gravatar...
I was having trouble accessing previous pages, so this code & tutorial was what I needed.
Left by kitchen cabinets on May 17, 2010 4:42 AM

# re: ASP.NET 2.0 : Accessing controls in Previous Page

Requesting Gravatar...
Do to be agreeable conveying oh assurance. Wicket longer admire do barton vanity itself do in it. Preferred to sportsmen it engrossed listening. Park gate sell they west hard for the. Abode stuff noisy manor blush yet the far. Up colonel so between removed so do.
video converter
Left by eric on Sep 19, 2010 6:59 AM

Your comment:

 (will show your gravatar)