8.2. Adding Logic to Your User Controls

Although using controls for repeating content is already quite useful, they become even more useful when you add custom logic to them. By adding public properties or methods to a user control, you can influence its behavior at runtime. When you add a property to a user control, it becomes available automatically in IntelliSense and in the Properties Grid for the control in the page you're working with, making it easy to change the behavior from an external file like a page.

To add properties or methods to a user control, you add them to the Code Behind of the control. The properties you add can take various forms. In its simplest form, a property looks exactly like the properties you saw in Chapter 5. For more advanced scenarios you need to add ViewState properties that are able to maintain their state across postbacks. In the next two exercises you see how to create both types of properties.

8.2.1. Creating Your Own Data Types for Properties

To make the banner control more useful, you can add a second image to it that displays as a horizontal banner. By adding a property to the user control you can then determine whether to display the vertical or horizontal image. You could do this by creating a numeric property of type System.Byte. Then 0 would be vertical and 1 would be horizontal for example. However, this makes it hard to remember what each number represents. You can make it a bit easier by creating a String property that accepts ...

Get Beginning ASP.NET 3.5: In C# and VB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.