How to call method/properties of one webpage to other using Cross page postback in ASP.NET

Our object is to access methods or properties of previous page using Cross page postback feature in

for example lets create two sample pages in our Web Application:
• Source.aspx
• Destination.aspx

<form id="form1" runat="server">

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" PostBackUrl="~/Destination.aspx" />
<asp:Label ID="lblInfo" runat="server" Text=""></asp:Label>


In .CS

public void SourceMethod()
lblInfo.Text = "Your Name is " + txtName.Text;

Now we have to call this sourcemethod from destination page and after this need to access lblInfo value.
For this:
Add following in destiantion page

<%@ PreviousPageType VirtualPath="~/Source.aspx" %>

We can be completely sure that we have a real CrossPagePostback ONLY IF:
1. Page.PreviousPage is NOT NULL,
2. PreviousPage.IsCrossPagePostback is true
This important to check to avoid errors in code.

protected void Page_Load(object sender, EventArgs e)
// first check if we had a cross page postback
if (Page.PreviousPage != null && (PreviousPage.IsCrossPagePostBack))
Source p = (Source)Page.PreviousPage;
lbl.Text = ((Label)p.FindControl("lblInfo")).Text;

No comments:

Post a Comment