Accessing Controls of Previous Page in C#

In this ASP.NET tutorial I will teach you how to get the previous page’s controls that in most of the cases you want to access.

Before arrival of Asp.Net 2.0, accessing the previous page's controls from a given page was almost not possible though we could get the controls’ values and transferred these values from one page to another using Sessions, HttpContext, even cookies in some scenarios.

Asp.Net 2.0 comes with a quite handy feature which is PreviousPage property. This is a public property of the Page class, and refers to the PreviousPage instance. Using this property, we can access the previous page's public properties.

We can get previous page's controls too with all its properties, so it’s up to you what you will do after accessing the previous page's controls that you want to access in your page.

I will use a custom function FindControl() that takes two parameters to access the controls of previous page. Let’s have a look over below mentioned example; we have a web page named as firstpage.aspx that has a text box and a button control. Please note that the button's PostBackUrl property is set to another page, it means when the button is clicked, the current web form will post back to the webpage mentioned in PostBackUrl property of the button.

In simple words if button is clicked the current form is submitted to the web page mentioned in the PostBackUrl property of the button.

Page1.aspx

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

<div>

<asp:TextBox ID="txt_Name" runat="server" Text="Adeel Fakhar">

</asp:TextBox>

<asp:Button ID="Button1" runat="server" PostBackUrl="~/page2.aspx" Text="Button" />

</div>

</form>


Now let’s have a look over page2.aspx where we are getting previous page’s controls.

Page2.aspx.cs


public partial class page1: System.Web.UI.Page
{
private TextBox myTextbox;
protected void Page_Load(object sender, EventArgs e)
{
myTextbox= this.FindControl("txt_Name", PreviousPage.Controls) as TextBox;
}


private Control FindControl(string controlID, ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.ID == controlID)
return c;
if (c.HasControls())
{
Control cTmp = this.FindControl(controlID, c.Controls);

if (cTmp != null)

return cTmp;
}
}
return null;
}

Now let’s understand the code of page2.aspx

1) I declare an object (myTextbox) of Textbox class
2) On Page Load event of the page2.aspx, I get the Previous Page’s control that I wanted to get which is txt_Name and assign this Control to the myTextbox using FindControl function, now myTextbox will behave exactly like the previous page's control which is in my case txt_Name.

Now you have got all the properties of the txt_Name in myTextbox, now it’s up to you which property you will get, as an example I am getting its value and assigning it to string variable which is myName

String myName;

myName = myTextbox.text;

So this is the way to access the previous page’s controls in c#

0 comments: