0

Possible Duplicate:
Send data from one page to another in C# ASP.Net

Hi I am trying to send data from one page to another in asp.net I found various methods of doing so and am gona try a few to se how they work but I seem to be getting an error on my first attempt.Here is my code:

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

I am sending the data from Default.aspx to Default2.aspx. At the Default2.aspx in the Page_Load method I wrote this to retrieve the data:

  if (Page.PreviousPage != null)
    {
        string txtBox1 = ((TextBox)Page.PreviousPage.FindControl("TextBox1")).Text;
    }

From what I read on MSDN this should work but I must be missing something because when I pres the button to send the data and Default2.aspx loads I get an error page that looks like this:

enter image description here enter image description here

Community
  • 1
  • 1
user1525474
  • 285
  • 1
  • 4
  • 8

2 Answers2

2

if you use master page for Default.aspx then Page.PreviousPage.FindControl doesn't work. Because when using masterpage, all controls in Default.aspx are placed in ContentPlaceHolder not directy in Form. So you can use below code:

Page.PreviousPage.Form.FindControl("yourContentPlaceHolderID").FindControl("TextBox1");

i assume you use masterpage. Otherwise your first code must work. In addition if you dont use masterpage and textbox is placed in PlaceHolder or Panel, your code won't work as well. FindControl doesnt recursively search in child container controls.

See the link. MSDN

bselvan
  • 384
  • 1
  • 4
  • 14
1

Page.PreviousPage is only available when using Server.Transfer to redirect to a new page. If this is a standard GET or POST, or Response.Redirect then this code will not work.

From your previous page. Use Server.Transfer to be able to access the previous page data.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • If I understand this corectly Server.Trasfer transfer the data to the second page.Right?If that is so isen't that what PostBackUrl="~/Default2.aspx" also does? – user1525474 Oct 07 '12 at 13:08
  • `Server.Transfer` loads a new page in the same request (remembers old page).`Response.Redirect` loads a new page in a new request (forgets old page). The [`PostBackUrl`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.postbackurl.aspx) on the button simply defines what page to post to. – Paul Fleming Oct 07 '12 at 13:10
  • I think what you want is just `((TextBox)this.FindControl("TextBox1)).Text;` or `this.TextBox1.Text;` – Paul Fleming Oct 07 '12 at 13:10