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 5-3, create the navigation bar user control described in Recipe 5.2, then create the .ascx file shown in Example 5-14, all without writing any VB or C# code.
Figure 5-3. Reuse of code-behind class output
The @ Control directive at the top of the .ascx page defines the code-behind class that will be used with the .ascx file. The Codebehind attribute defines the name of the file containing the code-behind class. The Inherits attribute defines the class in the codebehind file that inherits from System.Web.UI.UserControl and provides the codebehind 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 5.2:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CH05UserControlNavBarVB.ascx.vb" Inherits="ASPNetCookbook.VBExamples.CH05UserControlNavBarVB" %>
The user control can provide any desired user interface without changing any of the code-behind. 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.
Example 5-14. Reuse of code-behind class (.ascx)