Web User Controls

Last Updated: 2001

Note:
This section was written before I did any commercial work with Custom Controls. I really must get round to rewriting the whole thing. I think I could write an entire book on the subject now... :-)

User controls are basically normal .aspx web pages but with the extension changed to .ascx to prevent people running them directly.

To use a User Control on a web form, it must first be registered in the using page. This basically allows the definition of a namespace in which a particular user control will run so that we can don't have to worry about two user control class names being the same. Registration is (always??) performed at the top of the file and takes the form:

    <%@ Register TagPrefix="myNamespace" TagName="myControlName" Src="somePage.ascx" %>

Once registered the control can be placed on the page thus:

    <myControlName id="asUsual" runat="server" />

User Controls can be loaded dynamically:

    Control cntrlNew = LoadControl("myControl.ascx");
    Page.Controls.Add(cntrlNew);

To refer a property of the loaded control it is obviously necessary to cast it from the generic Control class to the correct class. The class name is declared in the user control page (not the page that uses the control) and is declared using the <@ Control ClassName = "somename" %> directive (which replaces the @Page directive). Once this is done, the new object can be cast as usual (e.g. ((somename) cntrlNew).SomeProp = "blah";)

Note: For casting to be available the control must have the corresponding Register line in the containing form. Having the URL that would have be included in the Register line in the LoadControl line is not sufficient.

Composite Controls

Custom Controls