ASP.NET Code Behind Pages, Part 2
By Mani Raja
In Part 1 we discussed, from a high-level, what the codebehind technique does and its advantages. We also looked at creating an .aspx page that contained just content. In this part we'll look at creating the code for the content!
Creating the "Code"
In the previous code example we created the content for our page. We used ASP.NET server controls to generate
two text boxes and a submit button. Our code, which will display a welcome message and validate the username/password
against a database table, will consist of a compiled C# class. Therefore, the code for CodeBehind.cs
will need to be compiled into a DLL, and that DLL will need to be put in the \bin directory.
To compile the code presented below, simply use the following command-line instruction:
csc /out:Codebehind.dll /r:System.dll,System.web.dll,System.Data.dll /t:library Codebehind.cs
|
You will then need to move the CodeBehind.DLL to the \bin directory.
The code for CodeBehind.cs follows:
|
As mentioned earlier, the entire page is a class derived from the ASP.NET Page class. The member variables have a one-to-one mapping with the Ids of the HTML and/or Web Controls in the calling ASP.NET page. The names of the Ids must exactly match with the names of the member variables in the derived page class. For e.g., the web control declaration for the TextBox:
<asp:TextBox id=txtPassword Width=200 Runat=server TextMode="Password" />
|
becomes:
public System.Web.UI.WebControls.TextBox txtPassword;
|
a member variable of the CodeBehind class.
The Page_Load event handler will be invoked on every request to the page.
The IsPostBack property is used to determine if the page is submitted to
itself.
if (!IsPostBack)
|
I used this property to set the Text in the Label Control when the page is
requested for the first time. The successive requests will not fall through
this block of code because IsPostBack will return true.
The actual programming logic resides in the btnSign_Click event handler. The
code inside this handler opens a connection to the database CodeBehind and
executes a SQL query that fetches the matching record from the table Users
for the given UserId and Password.
The SQL script to create the database table and populate data, the ASP.NET page, code-behind page and the batch file to compile the code-behind page are all available for download as a .ZIP file. To setup this sample program, follow the steps given below:
-
1.) Create a virtual directory and extract the .aspx and .bat files into that
directory.
2.) Create a sub-directory named
bin under your virtual directory. This is
where the .DLL file will be stored after you compile the code-behind page.3.) Execute the batch file
4.) Type in the .aspx file name in the browser
Hope that this article helps to understand the concepts and implementation of a code-behind file. Happy Programming!
Attachments:




