Dmitry Starchuk's Professional Blog
Development and Architect Experience

Ways to Add ascx custom user control to asp.net aspx page.

March 11, 2009 12:02 by Dmitry

I  tried different ways of adding user controls to aspx page. 

 

You can add  ascx custom user control to any aspx page in different ways:

 

1.       In Declarative manner by just dragging and dropping acsx control to aspx page.  This will create the code for you.

2.       You can manually register control on the aspx page declaratively. Here in my example I just add custom calendar control to my page.  Since I use master page you see I put custom control within Content.  Tagname and Tagprefix are the names you select yourself, however it is good to have meaningful names.  Using many controls you can group them using the same tagprefix

 

<%@ Register src="../Controls/Calendar.ascx" tagname="Calendar" tagprefix="uc1" %>

 

 

<asp:Content runat="server" ID="Schedule" ContentPlaceHolderID="Main" >

 

 

                  <asp:PlaceHolder ID="customcontrols" runat="server" />

                  <uc1:Calendar ID="Calendar1" runat="server" />

 

 

 </asp:Content>

 

3.       Sometimes you will need to add user control dynamically in code behind.   This gives you flexibility to manipulate user control and add it on demand in code behind.  First you will need to load control and then just add it as a child control to any existing controls.  If you just want to add it to the page I suggest just to create PlaceHolder what can be used to attach child  controls to it.

 

<asp:Content runat="server" ID="Schedule" ContentPlaceHolderID="Main" >

 

                  <asp:PlaceHolder ID="customcontrols" runat="server" />

 

           </asp:Content>

 

              protected void Page_Load(object sender, EventArgs e)

              {

                   Control contr = LoadControl("../Controls/Calendar.ascx");

                  this.customcontrols.Controls.Add(contr);

 

              }

              

4.  If you need to access properties of public method of created control you have to access strongly typed control.  In order to do that you need to register control in aspx page:

                <%@ Register src="../Controls/Calendar.ascx" tagname="Calendar" tagprefix="uc1" %>

And in code behind cretae instance of strongly type control by using the class name assigned in codebehind and casting it like this:

 

Controls_Calendar contr = (Controls_Calendar)LoadControl("../Controls/Calendar.ascx");

this.customcontrols.Controls.Add(contr);

 

 

 

 


Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

May 15. 2009 02:33

Vintage-style

I will try it, I wonder whether I can do it.

Vintage-style

Comments are closed