ASP.NET Code Behind Pages, Part 2By 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
will need to be compiled into a DLL, and that DLL will need to be put in the
To compile the code presented below, simply use the following command-line instruction:
You will then need to move the
CodeBehind.DLL to the
The code for
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:
a member variable of the
Page_Load event handler will be invoked on every request to the page.
IsPostBack property is used to determine if the page is submitted to
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
executes a SQL query that fetches the matching record from the table
for the given
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
2.) Create a sub-directory named
binunder 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!