4.3. Reusing Code-Behind Classes
Problem
You have several page sections that require identical code-behind but the user presentation must be different for each.
Solution
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.

Figure 4-3. Reuse of code-behind class output
Discussion
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"
Codebehind="UserControlNavBarVB1.ascx.vb"
Inherits="ASPNetCookbook.VBExamples.UserControlNavBarVB1" %>A significant aspect of this approach is that the user control can provide any desired ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access