ASP.NET User Controls Make your own controls by grouping other controls 1ASP.NET User Controls
What is a User Control? A user controls is a grouping of other server controls into a single-container control – User controls are composite – A user control contains child controls 2ASP.NET User Controls
How to create a User Control? Make a new folder ”Controls” Create a New Item -> User Control – Filename.ascx User controls are designer friendly – You can drag-and-drop child controls from the Visual Studio Toolbox to the control 3ASP.NET User Controls
When to create a User Control? A User Control is useful, if you have a set of controls that appears on many pages. You aggregate the individual controls in a new user control The user control can then be used in a number of pages 4ASP.NET User Controls
Using a user control Using a User Controls is like using any other server control User controls can be used wherever you can user other kinds of controls, like – Web forms – Master pages – Other (bigger) user controls User control must be registered – Register in single page – Register in web.xml 5ASP.NET User Controls
User control registration To use a User Control the User Control must be registered. Registration can be done in two places – In the file using the User Control – In web.xml Site-Wide registration 6ASP.NET User Controls
Site-Wide registration of user controls in web.config … … 7ASP.NET User Controls
User Control Properties User Controls can have properties Properties are declared in the code-behind of the user control Set in the page that uses the User Control – Declaratively from the page using the User Control – Programmatically from the code-behind of the page using the User Control – Get the value in the code-behind 8ASP.NET User Controls
User control events User controls can have events – Just like ordinary controls – Example: Events from sub-controls can be propagated to the user control Called ”Event Bubbling” – Event arguments can be empty, or carry data. Example: usercontrol/loginusercontrol ASP.NET User Controls9
Best practices Don’t overuse user controls – User controls encapsulate repeating content – UI + code spread over more files A user controls should focus on a single task Don’t hardcode style info (CSS) in a user control – Make a CssClass property for the user control ASP.NET User Controls10
Further reading, etc. Imar Spaanjaars Beginning ASP.NET 4 in C# and VB, Wrox 2010 – Chapter 8 User Controls, page ASP.NET User controls (video 1:19 min) – – User-Controls User-Controls Chris Peels Create a Custom User Control in ASP.NET (video 27 min, VB), 2007 – control-in-aspnet control-in-aspnet Bill Evjen et al. Professional ASP.NET 4 in C# and VB, Wrox 2010 – Chapter 25 User and Server Controls, page George Shepherd Microsoft ASP.NET 4 Step by Step, Microsoft Press 2010 – Chapter 5 Composite Controls, page ASP.NET User Controls