Recipe 5.4. 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 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


Discussion

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)

 <%@ Control Language="VB" AutoEventWireup="false"    CodeFile="CH05UserControlNavBarVB.ascx.vb"    Inherits="ASPNetCookbook.VBExamples.CH05UserControlNavBarVB" %> <asp:datalist  runat="server"  borderwidth="0" cellpadding="0" cellspacing="0" height="29"  repeatdirection="vertical" repeatcolumns="1"  repeatlayout="Table" width="150" horizontalalign="Left"  itemstyle-horizontalalign="Center"  OnItemDataBound="dlNavBar_ItemDataBound">  <itemtemplate>    <a  runat="server" >    <img  runat="server" border="0"      alt="" src="/books/1/505/1/html/2/"/></a>  </itemtemplate> </asp:datalist> 



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

Similar book on Amazon

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