Access Properties of Previous Page in ASP.Net

Sometimes we need to access the values from previous page. Generally we use Asp.net states.
 
But we can do this without using any kind of state mechanism.
 
.Net  has a feature called PreviousPage where we have to provide the name of the page of which we are going to access the properties from current page.
 
Suppose we have two pages (Default.aspx and Default2.aspx)
 
Start up page is Default.aspx where we have a textbox and a button.
 
On button click we are redirected to Default2.aspx where we can see the value typed in textbox of default.aspx.
 
Please refer code below.
 
Default.aspx
  1. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  2.       <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />  
Default.aspx.cs
  1.     /// <summary>  
  2.     /// Retrive value from previous page. This property is Readonly.  
  3.     /// </summary>  
  4.     public string MyName  
  5.     {  
  6.         get { return TextBox1.Text; }  
  7.     }  
  8.     protected void Button1_Click(object sender, EventArgs e)  
  9.     {  
  10.         Server.Transfer("default2.aspx");  
  11.     }  
In code we have a property named MyName which holds value of textbox1.
 
Now its time to access the value in another page Default2.aspx.
 
Default2.aspx 
  1. <%@ PreviousPageType VirtualPath="~/Default.aspx"  %>  
Here you can see we just have to add a markup in the design of the Default2.aspx page named PreviousPageType.
 
It has a property called  VirtualPath which accepts path of the previous page as string.
 
Default2.aspx.cs
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         if (PreviousPage != null)  
  6.         {  
  7.  
  8.             Response.Write(PreviousPage.MyName + "  Unique Id :" + PreviousPage.Title);  
  9.         }  
  10.     }  
  11. }  
Now its time to display values from previous page on page load. You can put it in any event of the page.
 
It is really simple and easy to understand.
Ebook Download
View all
Learn
View all