user495093
user495093

Reputation:

Add UserControl to page From another class

I have page and call method inside my page. I want to add some control to my page Control (not page itself) inside that method.

My Default.aspx :

<%@ Page Title="Home Page" MasterPageFile="~/Site.master"  ...  %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</asp:Content>

and Code Behind :

namespace Program
{
    public partail class Default : Page
    {
         protected void Page_Load(object sender, Eventargs e)
         {
              MyClass.Calling(this); 
         }
    }
}

my another class

namespace Program
{
    public class MyClass
    {
         public static void Calling(Page page)
         {
              Textbox txt = new Textbox()
              // I want somthing like this:
              // page.PlaceHolder1.Controls.Add(txt);
         }
    }
}

Is this possible?

Update: Thanks to @The King.

Upvotes: 2

Views: 612

Answers (2)

The King
The King

Reputation: 4650

I'm sorry about my previous answers not working to you.. I just wrote it from my memory... Here is a working solution... You first need to find the content place holder before finding your place holder...

Note : Please use ContentPlaceHolderID and not the ID of the Content Tag...

namespace Program  
{  
    public class MyClass  
    {  
         public static void Calling(Page page)  
         {  
            ContentPlaceHolder cph = page.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
            if (cph == null)
            {
                  return;
            }

            PlaceHolder ph = cph.FindControl("PlaceHolder1") as PlaceHolder;
            if (ph != null)
            {
                ph.Controls.Add(new TextBox());
            }
         }  
    }  
}  

Please refer to the revision history for my old answers...

Upvotes: 3

user284291
user284291

Reputation:

Have a look : ASP.NET Page Class Overview

Upvotes: 0

Related Questions