Recipe 4.3 Reusing Code-Behind Classes

     

4.3.1 Problem

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

4.3.2 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
figs/ancb_0403.gif

4.3.3 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 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.

4.3.4 See Also

Recipe 4.2

Example 4-14. Reuse of code-behind class (.ascx)
 <%@ Control Language="vb" AutoEventWireup="false"        Codebehind="CH04UserControlNavBarVB1.ascx.vb"        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"               itemstyle-horizontalalign="Center">   <itemtemplate>     <a id="anNavBarLink" runat="server" >     <img id="imgNavBarImage" runat="server" border="0"/></a>   </itemtemplate> </asp:datalist> 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2006
Pages: 179

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net