How to get a control on the previous page when it is a content page?

There are 2 pages Default.aspx and Result.aspx:

<!-- Default.aspx -->
<%@ Page Language="C#" AutoEventWireup="true"
MasterPageFile="~/Default.master"  CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<asp:Content ID="Content1" runat="server"
ContentPlaceHolderID="ContentPlaceHolder1">
    &nbsp;<asp:Label ID="Label1" runat="server" Text="Please input a
string here"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button"
PostBackUrl="~/Result.aspx" /></asp:Content>

//Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

<!-- Result.aspx -->
<%@ Page Language="C#" MasterPageFile="~/Default.master"
AutoEventWireup="true" CodeFile="Result.aspx.cs" Inherits="Result"
Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
    <asp:Label ID="Label1" runat="server" Text="The string you input in
the previous page is"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>

//Result.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Result : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            TextBox tb = (TextBox)PreviousPage.FindControl("TextBox1");
            if (tb != null)
                TextBox1.Text = tb.Text;
        }
    }
}

Both of these 2 pages have the property MasterPageFile set, but the
contents of Default.master is not important. There are 2 controls on
Default.aspx, a TextBox named TextBox1 to accept the input, a button
named Button1 and its PostBackUrl is set to Result.aspx. While
Result.aspx is loading, it tries to get the string the user inputted in
the previous page and shows it in TextBox1.

The problem is after executing the following statement, tb is set to
null:

TextBox tb = (TextBox)PreviousPage.FindControl("TextBox1");

I tried to replace this statement with the following statements:

Content con = (Content)PreviousPage.FindControl("Content1");
if (con == null)
    return;

TextBox tb = (TextBox)con.FindControl("TextBox1");

But con is null after executing, so the next statements are ignored.

How can I get TextBox1 on Default.aspx while Result.aspx is loading?
Thanks for any clues.

Regards,
George

0
George
7/6/2006 12:55:34 AM
asp.net.navigation-controls 13714 articles. 0 followers. Follow

3 Replies
635 Views

Similar Articles

[PageSpeed] 32

Without a shadow of a doubt, the best way to read a value from a control on a previous page is to encapsulate it with a property. That way you don't need to use FindControl, so it's much faster and more reliable when used within a master page environment. It also has the added benefit of providing OO encapsulation, so if you decide to change the control type on the previous page for some reason (say make it a combo box rather than a text box), you don't have to edit all the other pages and change all the casts.
Regards

Dave
0
DMW
7/6/2006 1:39:25 AM
I do agree with your opinion. But there is still one thing unexplainable: why FindControl can not find the expected control TextBox1?
0
George
7/6/2006 6:55:01 AM

That's easy to explain. When you use a MasterPage, the MasterPage is inserted into the content page as a user control. FindControl only finds a control within the current naming container (i.e. the page), not any nested naming containers.

You have to navigate down through the control tree until you find the content place holder control, and then call FindControl on that. Alternatively, create a method that recurses through the controls calling FindControl at each level.


Regards

Dave
0
DMW
7/7/2006 12:56:47 AM
Reply:

Similar Artilces:

Problem to use TreeView Control in a 'content page' This Error Occur "Only Content controls are allowed directly in a content page that contains Content controls."
hi I am trying to use the TreeView Control inside the content page (Page that has a master page is a content page). On compiling the project I got the following ASP.Net runtime error: "Only Content controls are allowed directly in a content page that contains Content controls."B@b@R J Issue resolved. I was putting script tag in the content page that is not allowed. when remove the script from content page problem is resolved.B@b@R J...

Content controls have to be top-level controls in a content page or a nested master page that references a master page.
Why in the world am I getting this error? The solutions I have seen either don't apply or don't work.  Here is my master page code:<%@ Master Language="C#" AutoEventWireup="false" CodeFile="TechLMSMasters/MainSide.master.cs" Inherits="MainSide" %> <%@ Register TagPrefix="usercontrol" TagName="Search" Src="~/library/uc/Search.ascx" %> <%@ Register TagPrefix="usercontrol" TagName="UserName" Src="~/library/uc/UserNameDisplay.ascx" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"></asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> <DIV class="user" id="userName" runat="server"><usercontrol:username id="userNameDsp" runat="server"></usercontrol:username></DIV> <DIV class="search" id="search" runat="server"><usercontrol:search id="pageSea...

Error : Content controls have to be top-level controls in a content page or a nested master page that references a master page.
when I make a directory on my root, and in that directory I put a masterpage and a web form ... I get always an error : Content controls have to be top-level controls in a content page or a nested master page that references a master page.   Does somebody know what the problem is ? Is it possible you can't set a masterpage in a directory ... ?Kind Regards,Joeri Pansaerts.From Bruges, Belgium :) i've founded ... I had to nest my masterpage ...Kind Regards,Joeri Pansaerts.From Bruges, Belgium :) Hi Joeri Pansaerts, I am receiving the same error as the one posted her...

ERROR Content controls have to be top-level controls in a content page or a nested master page that references a master page.
This all used to work until about 5 minutes ago. Did I change something? For some reason I am now getting this error: Content controls have to be top-level controls in a content page or a nested master page that references a master page. What I have:  I have a masterpage inside of a directory. That directory is a first level directory with its own web.config file....The whole thing is protected by the web.config file above it (in the main public directory). That main public directory has a masterpage as well. I am not currently linking the two masterpages together becuase...

Control of the page and the controls on a page
I am building a web app that has some pages that are public and some that are only available based on subscription. Could someone explain the best way (infrastructure wise) how to control whether a server control is visible or enabledand how to control whether a page is viewable or not based on the user and whether or not the user is logged in (or not). If a user is not logged in I would like some controls to be visible but disabled. I also have to control the URL's in case a person learnsthe URL and tries to type it in. My question is more towards how to do this database wise. I am u...

convertion from page to content page or from user control to content page
Hi, I have converted an asp.net 1.1 application to 2.0.  Now what I am looking for some enhancement.  I added a master page and now I want to add other pages as content pages. but those pages which I am converting into content have some user control. Now either I can convert those user control to content pages ( which i want to look for if it is possible),  Or I am thinking i shouldn't convert those user control to content pages cause they might be just good. So looking for some of those people opinion who have worked through this so can I get opinion here please.thanks&nb...

i have 3 pages student information , i filled two pages ,then go to 3rd page . First Two pages iam having 100 controls.how to store that controls and how to send these controls into 3rd page in ?
i have 3 pages student information , i filled two pages ,then go to 3rd page . First Two pages iam having 100 controls.how to store that controls and how to send these controls into 3rd page in ?  There are a number of ways storing values. Check out: http://msdn2.microsoft.com/en-us/library/75x4ha6s.aspxhttp://www.csharphelp.com/archives/archive207.html Thanks,Karan~ Remember To Mark The Post(s) That Helped You As The ANSWER ~ Hi, Welcome to asp.net forums. Now as far as your requirements goes, the first thing that strikes me is that 100 controls are way too many to kee...

Calling a method from a control page on the axpx page where the control page exists.
Hello,  I have an .aspx page that has a method called grdMain_DataBind().  I have a control page that loads within the aspx page which has its own logic.  I have a button on my control page called "SAVE".  How can I call the method grdMain_DataBind thats in my aspx logic from the control that exists on that page when I click SAVE button.  Is there a way? If I were you, I'd simply create a "Save" Event within your control. When the Button in your control is pressed, in the Click handler for that Button you can raise the event. Then, within t...

Only Content controls are allowed directly in a content page that contains Content controls.
 Hi all,I am using gridview to display data add i am using checkbox so that when a person  chech  the box it display information regarding that.At local server its run fine but when i upload this on website it gives following exception.Offending URL: http://www.vcsmindia.com/studentRegistrationDetails.aspxSource: System.WebMessage: Exception of type 'System.Web.HttpUnhandledException' was thrown.Stack trace: at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPo...

Only Content controls are allowed directly in a content page that contains Content controls.
Hi Friends, I created one Master Page.In this I created one Default.aspx .Here I added Content Place Holder,here I am doign the program which is realted to Regisration  Form. I wrote the javascript in source code of content place holder.But its not supporting the java script and its showing the errors in the script(it is in bold in the following source code)I wrote the code like following<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title=&qu...

Only Content controls are allowed directly in a content page that contains Content controls.
Hello I got this error message whenever I place this script below on my inline code: this.RegisterClientScriptBlock("keyClientBlock", "<script>alert ('Javascript block of code executed')</script>");             Please advice.Thanks  Try this: this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "script");HTH   My Blog Thanks for the reply but doesn't work for me :(I tried placing the script on string variable before...

Show content in both Master Page ContentPlaceholder AND Content Page Content control
I note that by default or rendering rules, when you add content/controls to the Content Page ASP:Content control matched to a Master Page ContentPlaceholder, any content/controls in the matching Master Page ContentPlaceholder is not displayed. Is there a setting that can be made to merge or show both content/controls in the Master Page ContentPlaceholder and content/controls in the matching Content Page Content control? Thanks         Don't think so. If you specify a content control in your page then whatever is in there displays and anything in the matching contentplaceholder does not display. If you wan tthem both to display why don't you put whatever you currently have in the contentplaceholder on the masterpage directly onto the master page (or into a regular placeholder on the master page if you want to be able to show and hide it based on something going on) and then leave the contentplaceholder empty and that way when your page is rendered you'll always get both sets of content renderd (unless you put the stuff you currently have in the contentplaceholder in a placeholder and set its visibility to false.)  If this post answered your question please remember to 'Mark as Answer'!...

Need to access a Label Control on the Master Page from a user control attached to a content page
Hello all, I have a master page (say  site.master)  with a status Label in it. I have a content page ( say content.aspx)  that has a user control (say usercontrol.ascx). One of the Button Click Events in the usercontrol.ascx needs to pass on some text onto the status label on the masterpage(LabelStatusMsg) and display it. I have been able to do this directly off a content page (content.aspx) by using the following code (VB)  on the master page <%@ MasterType virtualpath="~/site.master" %> and Dim mpLabel As Label = CType(Master.FindControl("LabelStatusMsg"),...

How do i get master page's Controls value into Content page!!!
  Hi to All,   I have a Master Page that Contains 4 dropdown lists and 2 Checkboxlists(that contains lot of check box list items) and one Search Button. now i want to search according to master page's controls parameters and display it on content page.now my problem is how do i get the master page's controls(dropdown lists,Checkboxlists)  values into content page. i did use properties for that in master page and calling these properties in  content page like this: Master.master:public string RegionState { get {if (Session["regionState"] == nu...

Only Content controls are allowed directly in a content page that contains Content controls. #2
Hi, Trying to add:  Response.Write("<script language='javascript'>window.open('PO_export.asp?C=" + sql + "'); </script>") Getting error (in subject).  Anyone help? Thanks, Mark Why don't you try to add the javascript in the head section of the page.Bind GridView to Dynamically created DataTable | Bind DataTable to DropDownListMy Blog Hi Mark, Based on your description, the issue is error message appears when you add JavaScript code to the content page. After reviewing your code, I find nothing wrong with it. I...

Content controls are allowed only in content page that references a master page.
HiI'm getting the above error with my application.Basically I had a master file and then some page files referencing the master file.In the page files I had some ajax controls so had :<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><atlas:ScriptManager ID="ScriptManager1" runat="server"></atlas:ScriptManager>in them.but when I try adding an ajax control to the master file and putting the above code in, it shows the error messagewhy would this be?thanks!  Make sure you have prop...

how to pass ddl1.selectedvalue from a content page to a User Control page ( ascx page)
 Hi All,I have a DropDownList in a content page. i would like to access its selectedvalue my user control page. the below is DDL<asp:dropdownlist id="ddl1" runat="server" autopostback="true">            <asp:listitem value="6" >6</asp:listitem>            <asp:listitem value="12" >12</asp:listitem>            <asp:listitem value="24"...

error: Content controls are allowed only in content page that references a master page.
 I have a website that uses a masterpage. most of my users have no problem; but few get the error bellow. I was never able to duplicate the error.   ex.message: Content controls are allowed only in content page that references a master page.Stack trace:    at System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection)   at System.Web.UI.Page.get_Master()   at System.Web.UI.Page.ApplyMasterPage()   at System.Web.UI.Page.ProcessRequestMain(Boolean in...

Error:Content controls are allowed only in content page that references a master page?!!
 Hello All I have a web application, it is working well in localost without any error but when I upload it to the host it show me the error below:Any suggestion? I have not seen this error beforePlease any helpRegards, Server Error in '/' Application. Content controls are allowed only in content page that references a master page. Description: Anunhandled exception occurred during the execution of the current webrequest. Please review the stack trace for more information about theerror and where it originated in the code. Exception Details: System.Web.HttpException: Content controls are allowed only in content page that references a master page. Source Error: An unhandled exception was generated during the execution of thecurrent web request. Information regarding the origin and location ofthe exception can be identified using the exception stack trace below. Stack Trace: [HttpException (0x80004005): Content controls are allowed only in content page that references a master page.] System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection) +2028811 System.Web.UI.Page.get_Master() +48 System.We...

Using controls from pages, master pages, and user controls
How would I structure my site in this scenario: I'd like to use a dropdownlist all over my site, sometimes in a regular page, sometimes in a master page, and sometimes in a user control.  I wish to bind its events programmatically, so normally I would just put that in the codebehind.  However, I notice a lot of code duplication because I have to declare the control in everywhere, in my base page (which all my pages inherit from), in my base master page (which all my master pages inherit from) and in my base user control (which all my user controls inherit from).How should I be...

Trigger a control in Master from control in content page?
Hi!So how can I trigger the button click (or change hidden field?) in Master page from the button click event in content page? I need that because I have a popupcontrol in master page. I set it like this to have a "Add to cart" functionality - the button is in content page and the cart (popup) is in master. Like in gap.com... Been trying to figure that one out for days..  hiif you want to access a control which is in the master page from a client page..then you write a code like thisImageButton imgButton = (ImageButton)Master.FindControl("imageStep4");imgButto...

Get a control in the masterpage or page from the current page
Just thought I would post this.  You use it like this if you were looking for a TreeView. GetControl g = new GetControl(); Control tvSel = new Control(); if (g.getControlByName(this, ref tvSel, "tvSel")) if(((TreeView)tvSel).SelectedNode!=null) lbl.Text = "Selected: " + ((TreeView)tvSel).SelectedNode.Text; else lbl.Text = "Control Found but Not Selected"; else lbl.Text = "Control Not Found";     And here is the class:     public class GetControl { public GetControl() { } /// &...

Get page controls property in User control
I have a aspx page and there is a button. I want to access this button properties in my User control. How can I do so.Yes the user control is on my aspx page You can find the button with the FindControl method. Button btnFoo = (Button)Page.FindControl("buttonId"); string id = btnFoo.id;Please remember to click “Mark as Answer” so I know if my answer was good enough for you. Thanks.  this does not work. It returns me null.To be clear button is on my web page aspx and want to access its properties on the user control ascx Is you button nested in other controls? (eg...

Master Page and Dynamic Controls in Content Page
 I have a user requirement where i am creating dynamic control in the page that uses a master page. (Something Like ShowQuizQuestion.aspx which uses Master.Master). Now i have placed one ContentPlaceHolder in Master Page. Now During Page_Load of ShowQuizQuestion.aspx i am creating two dynamic textboxes. ShowQuizQuestion also contains a button(which is not dynamic).At the button_click event i want to trap the values of both textboxes in 2 different string variables.  When i create a standalone page! things work perfectly fine... but with use of masterpage it gets difficult since it ...

Web resources about - How to get a control on the previous page when it is a content page? - asp.net.navigation-controls

List of Presidents of the United States by previous experience - Wikipedia, the free encyclopedia
Although many paths may lead to the Presidency of the United States , the most common job experience, occupation or profession of U.S. presidents ...

App Center recommendation engine drives more repeat app users than previous Facebook games dashboard
... that users who discover apps through App Center are 40 percent more likely to return to the app the next day compared to users of the previous ...

Policy Talks @ the Ford School. Lecture by John Negroponte, a career American diplomat, previous US National ...
Policy Talk @ the Ford School, held on Thursday, February 27, 2014. The Lecture featured John Negroponte in a conversation on leadership and ...

Wheat and chaff: Arabian Gulf's previous attempts of cultivating crop
Concerns about food security have prompted trials of wheat cultivation. But previous attempts to grow the crop in the region have not fared well. ...

Sheikh's previous ALP membership revealed
ACT Greens senate candidate Simon Sheikh has conceded he was previously a member of the Labor party before becoming a self-proclaimed independent ...

Labor frontbencher Andrew Leigh shifts position on previous support for a GP fee
One of Labor&#8217;s chief economic spokespeople, shadow Assistant Treasurer Andrew Leigh, was once a strong supporter of a compulsory fee for ...


Stephen Moore shrugs off previous poor starts to season for Wallabies
There is a small but irritating fly in the ointment heading into the Wallabies' bid to notch five Test wins in a row for the first time since ...

Nick Kyrgios sledge of Stan Wawrinka due to previous bad blood, says Nill Kyrgios
Nick Kyrgios' mum, Nill, admits it was &quot;not a nice thing&quot; her son said to opponent Stanislas Wawrinka, but she felt there was previous ...

Debate ratings fall short of previous battles
Sunday night's stoush between Kevin Rudd and Tony Abbott was hard to avoid – carried on no less than seven channels – but avoid it many Australians ...

Resources last updated: 2/17/2016 11:57:03 PM