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.

posted @ Monday, April 25, 2005 8:01 AM

Print

Comments on this entry:

# re: Whidbey: Accessing controls in Previous Page

Left by Rosdi at 3/1/2006 10:17 AM
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..

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

Left by şişme bebek at 11/20/2008 1:16 PM
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

Your comment:



 (will not be displayed)


 
 
 
 
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345