4.3. Reusing Code-Behind Classes


You have several page sections that require identical code-behind but the user presentation must be different for each.


Create a user control for the first page section. For the other page sections, create only the .ascx file and link it to the code-behind class for the first page section. For example, to produce the vertically oriented navigation shown in Figure 4-3, create the navigation bar user control described in Recipe 4.2, then create the .ascx file shown in Example 4-14, all without writing any VB or C# code.

Reuse of code-behind class output

Figure 4-3. Reuse of code-behind class output


The @ Control directive at the top of the .ascx page defines the code-behind that will be used with the .ascx file. The Codebehind attribute defines the name of the file containing the code-behind code. The Inherits attribute defines the class in the code-behind file that inherits from System.Web.UI.UserControl and provides the actual code-behind code.

By changing the Codebehind and Inherits attributes of the .ascx file, you can reuse code. In our example, the attributes are set as shown here to reuse the code-behind from Recipe 4.2:

<%@ Control Language="vb" AutoEventWireup="false" 
                           Inherits="ASPNetCookbook.VBExamples.UserControlNavBarVB1" %>

A significant aspect of this approach is that the user control can provide any desired user interface without changing any of the code-behind. The only requirement is that the server controls referenced in the code-behind class must be present in the .ascx, and they must be of the same type. Leaving a server control out of the .ascx or changing its type will result in an exception being thrown.

See Also

Recipe 4.2

Example 4-14. Reuse of code-behind class (.ascx)

<%@ Control Language="vb" AutoEventWireup="false" 
      Inherits="ASPNetCookbook.VBExamples.CH04UserControlNavBarVB1" %>
<asp:datalist id="dlNavBar" runat="server"
              borderwidth="0" cellpadding="0" cellspacing="0" height="29"
              repeatdirection="vertical"  repeatcolumns="1" 
              repeatlayout="Table" width="150" horizontalalign="Left"
    <a id="anNavBarLink" runat="server" >
    <img id="imgNavBarImage" runat="server" border="0"/></a>

Get ASP.NET Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.