Custom Controls and User Controls

Custom Controls and User Controls both have sense of " customized" control. There is a bit of confusing, isn't it?  Well, myself have developed a couple of user controls for my projects. I did quite frequently referring them as Custom
Controls
..which is wrong. Those are actual User Controls.

Custom Controls are deriving from either System.Web.UI.Control or System.Web.UI.WebControls.WebControl. (Webcontrols have additional UI properites). They are customized by overriding the Control's Render method with HtmlTextWriter. User Controls are basically .ascx files.

A simple Custom Control:
using  System; 
using  System.Web.UI; 
using  System.Web.UI.WebControls; 

namespace  MyCustomControl 

     
public class MyCustomControl : Control 
     

            
protected override void Render( HtmlTextWriter writer) 
            

             writer.Write(
"My New Custom Control!"); 
            }
 
     }
 
}


To use this custom control in your page,  you need to register it with Register directive before you can use it.

<% @ Register TagPrefix = " MyControl "  Namespace = " MyCustomControl "  Assembly = " MyCustomControl "   %>  
< html >  
< body >  
     
< form runat = " server " >  
        Most introductory applications output: 
        
< MyControl:MyCustomControl runat = " server "   />  
     
</ form >  
</ body >  
</ html >

User Controls are quite frequently some header and footer files.  e.g. footer.ascx
<%@ Control Language="VB" %>
<p align="left">
    
<font size="1">© 2004 , AAA Inc.
    
<br />

    Comments and suggestions, please forward to ME
</font>  
</p>


You can drag the footer.ascx directly into your page, while Visual Studio will take care of the registration and implementation. e.g.
<% @ Page language = " c# "   %>  
<% @ Register TagPrefix = " uc0 "  TagName = " Footer "  Src = " Footer.ascx "   %>
< html >  
< body >  
     
< form runat = " server " >  
      
< uc0:Footer id = " UserControl1 "  runat = " server " ></ uc0:Footer >  
     
</ form >  
</ body >  
</ html >

It worths to metion that, a User Control with VB.NET can be used  in C# pages.

Not only header and footer are common User Controls, but any .aspx page can be converted to a User Control by changing

<% @ Page Language = " VB "   %>

into

<% @ Control Language = " VB "   %>

Just write this article to clear some concepts in my mind on the road to prepare 30-315 exam. Hope helps someone.

你可能感兴趣的:(user)