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
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
- <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Default.aspx.cs
-
-
-
- public string MyName
- {
- get { return TextBox1.Text; }
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- Server.Transfer("default2.aspx");
- }
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
- <%@ 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
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- if (PreviousPage != null)
- {
-
- Response.Write(PreviousPage.MyName + " Unique Id :" + PreviousPage.Title);
- }
- }
- }
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.