<%@ Page Language="VB" Inherits="codejunkies.myPage"
%>
Download the sample source
code here.
Code Behind has been a hot topic for ASP.NET since it was announced. Basically code
behind allows you to build an ASP.NET page from two files, a
presentation file and a code file. The presentation file is the .aspx or .ascx
(for user controls) file, and the code file ends in .vb (Visual Basic) or .cs
(C#). Building a single page from two files in this manner allows you to
completely separate the code and content. Additionally it provides some
mechanisms for protecting your code when selling a web application. In this
tutorial I will show you how to use code behind in both Web Forms and user
controls.
Sometimes the best way to learn something new is to jump right into it. Rather
than having you read a bunch of detail about how and why code behind does what
it does, I would rather have you get your hands dirty by writing some code. In
this tutorial you will be building four files, a Web Form, the code behind for
the Web Form, a user control, and the code behind for the user control. Lets
start with the Web Form. Listing 1.1 shows the Web Form code.
Listing 1.1 - Web Form Code: File Name - 2001012601.aspx
<%@ Page Language="VB" Inherits="myPage" Src="2001012601.vb" %>
<html>
<body style="font: x-small Verdana, Arial, sans-serif;">
<form runat="server" method="post">
<asp:label id="soonToBeUserControl" runat="server" />
</form>
</body>
</html> |
Break It Down
In Listing 1.1 you create a simple Web Form. It has one server control, a Label
named
soonToBeUserControl. The more interesting part of this
Web Form is the first line. In the
@ Page
directive you specify an
Inherits
property and a
Src
property.
-
Inherits
- Identifies the class name that this page will inherit from
-
Src
- Identifies the source code file that the class is in
In Listing 1.1 you indicated that this page will inherit the class
myPage
which is in a file in the same directory, named 2001012601.vb.
|
HEY!!!! I use Visual Studio.NET and it
automatically puts a CODEBEHIND property in my @ Page directive, not a Src
property!!! What Gives?!?
Hold on!!! There is a good reason for this. Let me cover a few
more basics, then I'll tell you why Visual Studio.NET does this.
|
This is all the code you need for the Web Form. Let's move on the the code
behind file for the Web Form. In Listing 1.2 you create the code behind file.
Listing 1.2 - Web Form Code Behind: File Name - 2001012601.vb
Option Strict Off
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Public Class myPage : Inherits Page
Public soonToBeUserControl As Label
Public Sub Page_Load(Source As Object, E As EventArgs)
soonToBeUserControl.Text = "Test"
End Sub
End Class |
In Listing 1.2 you create the code behind file for the Web Form in Listing 1.1.
I had you turn
Option Strict
off because of some things we will be doing later in this tutorial. You
imported the namespaces needed to make the code behind file work. Actually, one
of them (can you guess which one) is not needed for this page. That is the
System.Web.UI.HtmlControls
namespace. The reason it is not needed is that in this example you are not
going to be interacting with and classes in it. I had you put it in because it
is a good habit to build. Inevitably, if you are like me, you will not put it
in, then in a later revision of the code, make use of a class in the
HtmlControls
namespace but forget to import it. Then you get to figure out why a class that
exists is getting a "User-Defined type not defined" error. If you get in
the habit of importing it you will have more time for Nerf gun fights
later...trust me.
The
System
namespace gives you access to the basic system classes, the
System.Web.UI
namespace gives you access to the
Page
class (among others), and the
System.Web.UI.WebControls
namespace gives you access to the ASP.NET server control classes, such as
Label.
After importing all the namespaces you begin the class definition. You named
this class
myPage
and specified that this class inherits the
Page
class (from
System.Web.UI). While the
Page_Load()
event handler looks normal enough, it wouldn't work if you forgot to declare
soonToBeUserControl
as a
Label
type. This is one of the stumbling blocks with code behind. While you have
identified
soonToBeUserControl
as a
Label
in the Web Form via an
ID
property, it also must be defined in the code behind class, and its
System.Web.UI.WebControls
class referenced. You only need to declare controls that you will be
programmatically referencing in the class. You can have as many controls as you
would like on the Web Form, but you only need to declare the ones you want
programmatic access to in the code behind class.
If you view the page in the browser now you will simply see a page with the word
"Test" on it. When you made the request for the page, the .NET Framework parsed
the
@ Page
directive, found the file specified in the
Src
property, compiled the code, and rendered the output as if they had been one
file. When you deploy this Web Form to a different server, it is critical that
the code behind page also get deployed. The
Src
property of the
@
Page
directive indicates to the .NET Framework that the page should be assembled and
compiled on demand. If you are interested in hiding the class file from the
owner of the web server (such as a client) you can leave the
Src
property off and precompile the class file into the application's DLL. Without
a
Src
property the .NET Framework assumes the class is already compiled.
If you are precompiling the DLL, you will need to alter the Inherits property of
the
@ Page
directive to specify the namespace and class name the page inherits from.
For example, if I my project is named
codejunkies, then my
@ Page
directive would read:
|
In Visual Studio.NET when a new Web Form is created both the
Inherits property and a CODEBEHIND property are added to the @ Page directive.
The CODEBEHIND property is a property used by Visual Studio.NET to track the
location of the original class file. The .NET Framework ignores this property.
Since there is no Src property, the code behind class files must be precompiled
into a DLL before the page will work.
|
User Control Code Behind
Just like an ASP.NET Web Form, user controls can use the code behind technology
as well. For the most part the process is the same as the code in the previous
examples. The only real difference is the Inherits command in the class
definition. In Listing 1.2 you inherited the
Page
class since the code behind was for a
Page
object. In the code behind for a user control you will inherit the
UserControl
class from the
System.Web.UI
namespace. Listing 1.3 shows the user control
.ascx
file.
Listing 1.3 - User Control: File Name - 2001012601uc.ascx
<%@ Control Inherits="myUserControl" src="2001012601uc.vb" %>
<p><asp:Label runat="server" id="myLabel" /></p>
<p><asp:DataGrid runat="server"
id="myDataGrid"
Font-Size="x-small"
HeaderStyle-Font-Bold="True"
HeaderStyle-ForeColor="White"
HeaderStyle-BackColor="Brown"
AlternatingItemStyle-BackColor="Tan"
/></p> |
In the user control in Listing 1.3 you place a Label control and a DataGrid
control. You will be accessing these from the code behind class. In the first
line of the user control you use the
@ Control
directive's
Inherits
and
Src
properties to set the code behind values. Listing 1.4 shows the code from the
user control code behind file.
Listing 1.4 - User Control Code Behind: File Name - 2001012601uc.vb
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient
Public Class myUserControl : Inherits UserControl
Public myDataGrid As DataGrid
Public myLabel As Label
Public Property myProp As String
Get
Return myLabel.Text
End Get
Set
myLabel.Text = Value
End Set
End Property
Public Sub Page_Load(Source As Object, E As EventArgs)
Dim ds As New DataSet
Dim sda As SqlDataAdapter
sda = New SqlDataAdapter("SELECT CompanyName, ContactName,
ContactTitle FROM Customers",_
"server=localhost;uid=sa;pwd=;database=Northwind;")
sda.Fill(ds, "Customers")
myDataGrid.DataSource = ds.Tables("Customers")
myDataGrid.DataBind()
End Sub
End Class |
In Listing 1.4 you created the code behind class for the user control. As with
the Web Form code behind class, you import all the necessary namespaces. In the
class definition you inherit the
UserControl
class rather than the
Page
class. Both server controls in the user control are defined in the class so you
can programmatically access them. I had you create a property for the user
control named
myProp. You will be accessing the user control's
property from the Web Form's code behind class.
At this point, if you view the page you will not see the user control show up.
This is because you have not added the user control to the Web Form. You could
just register the user control on the Web Form and place it somewhere on the
page, but you would not be able to programmatically access the user control to
set the
myProp
value. Instead you are going to use the Label control in the Web Form as a
place holder for the user control, and dynamically load it. Listing 1.5 shows
the revised code behind class for the web form.
Listing 1.5 - Revised Web Form Code Behind: File Name - 2001012601.vb
Option Strict Off
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Public Class myPage : Inherits Page
Public soonToBeUserControl As Label
Public Sub Page_Load(Source As Object, E As EventArgs)
'Dynamically load the user control to the Page's Controls
collection
Dim tempUserControl =
Page.LoadControl("2001012601uc.ascx")
'Set the user control's myProp value
tempUserControl.myProp = "This property was set in Code
Behind"
'Add the user control to the Label's Controls collection
soonToBeUserControl.Controls.Add(tempUserControl)
End Sub
End Class |
In Listing 1.5 you use the Label control in the Web Form as a place holder for
the user control. By dynamically loading the user control you have programmatic
access to its properties and methods. Notice that when the variable for the
user control was defined, a data type was not used. This requires that
Option
Strict
be turned off. This allows the object to inherit the properties and methods of
the user control when it is loaded. Once the user control is loaded into the
Page's
Controls
collection, and the property value is set, you add it to the Label's
Controls
collection which places it on the page where the Label control is.
Viewing the Web Form in the browser now you will see the text "This property was
set in Code Behind" which is the
Text
value of the Label control in the user control, as well as the DataGrid in the
user control. Figure 1.1 shows the rendered output.
Figure 1.1 - Using Code Behind with a Web Form and a User Control

Summary
Code behind is one of the great technologies brought to developers
with the .NET Framework. It truly enables complete separation of code and
content. The code files can exist on the web server and the pages will be
compiled on demand (using the
Src
property), or the code behind files can be precompiled and the classes will be
completely hidden from a client (omitting the
Src
attribute).