Using of UserControls as WebParts

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

By using implementing of some more complex web application you will probably have a requirement to integrate web parts in your application. Unfortunately ASP.NET 2.0 based web parts, are derived from the Web Part class which implicitly derives from WebControl and not from UserControl.

 

The big difference between WebControl and USerControl (ASCX) is that WebControl-s can be easily deployed (distributed in DLL) and UserControl-s not.

On the other hand, the Visual Studio provide the full designer support for UserControls, but not for WebControl-s.

Personally, I would rather have one type of control only which provides both functionalities.

 

After this short intro, let’s go back to the “web part requirement”. Because the web part is a WebControl you can distribute it, but implementation of common graphic staffs will be painful.

 

To avoid this problem Microsoft offered the possibility to host the UserControls as web parts in one Web part zone as shown in this example:

 

<ZoneTemplate>

<asp:TextBox Title="TextBox Gadget" ID="TextBox1" runat="server"></asp:TextBox>

<asp:Calendar Title="Calendar Gadget" ID="Calendar1" runat="server"></asp:Calendar>
                 

 </ZoneTemplate>

 

 

This example shows how to embed two controls (text-box and button), which will appear as two web parts. To make this working the ASP.NET creates the GenericWebPart control for each control specified in the zone template. Each specified control is then added as the child control of the generic web part instance and is treated as a single web part.

 

To transform the control in real web part, you can additionally implement the interface IWebPart. This interface extends the control with some (but not all) of web part properties (CatalogImageUrl, Description, Subtitle, Title etc).

 

Last but not least, the web part usually provides some custom properties, which can be edited in edit mode. To provide such properties just implement following in the user control code:

 

 

        [WebBrowsable]

        [Personalizable(true)]

        public string MyProperty

        {

            get { return “...”; }

            set { ... = value; }

        }

 

 

This property is visible and changeable in the edit mode. Additionally it is personalizable too.

 

 

 

 


Posted Sep 19 2006, 03:11 PM by Damir Dobric
Filed under:
developers.de is a .Net Community Blog powered by daenet GmbH.