开发者

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" C开发者_如何学运维ontentPlaceHolderID="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.


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...


Have a look : ASP.NET Page Class Overview

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜