Reputation: 16629
I have Page1.aspx
containing
Name: <asp:TextBox ID="txt1" runat="server" />
Page2.aspx
tries to access its contents by
TextBox txt2 = (TextBox)PreviousPage.FindControl("txt1");
However I end up getting an Object reference not set to instance of an object exception
Upvotes: 1
Views: 5097
Reputation: 262
Once your'e in the new page, the last page is probably gone, I'd suggest transferring your data over the session.
Upvotes: -2
Reputation: 3706
I've used PreviousPage
before and have had success with this snippet of code I found elsewhere online (Can't remember where I found it!)
So..
Option 1:
On your first page you have your button that takes you to the second page, you need to set the PostBackUrl
property to the new page url:
<asp:Button ID="button1" Runat="server" Text="submit" PostBackUrl="~/Page2.aspx" />
(This is presuming that your 1st page is a form that redirects to your Page2.aspx)
Then in the new page's code behind you need to write something along the lines of this:
public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl("txt2");
Response.Write(tb.Text);}
}
You will need to transfer the value of the previous page's txt2.Text
to a textbox or label on the new page if you are wanting to do any more postbacks on the second page, otherwise you will lose that value.
Option 2:
You could also use a Session variable surely to store your data?!
Session["text"] = txt2.Text;
Upvotes: 3