Published: Thursday, October 05, 2000
ASP.NET Code Behind Pages, Part 2
By Mani Raja
Read Part 1
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:
namespace ASPPlus
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SQL;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public class CodeBehind : System.Web.UI.Page
{
public System.Web.UI.WebControls.Label Message;
public System.Web.UI.HtmlControls.HtmlTable tblSignIn;
public System.Web.UI.WebControls.TextBox txtLogin;
public System.Web.UI.WebControls.RequiredFieldValidator RFVLogin;
public System.Web.UI.WebControls.TextBox txtPassword;
public System.Web.UI.WebControls.RequiredFieldValidator RFVPassword;
public System.Web.UI.WebControls.Button btnSignIn;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Display welcome message
Message.Text = "Enter Login and Password";
}
}
protected void btnSignIn_Click(Object obj, EventArgs e)
{
if(Page.IsValid)
{
// check username/password against a database table
SQLConnection conn = new
SQLConnection("server=localhost;uid=sa;pwd=;database=CodeBehind");
// get row back based on username/password
string strSQL = "Select * From Users Where UserId='" +
txtLogin.Text + "' And Password = '" +
txtPassword.Text + "'";
SQLDataSetCommand dsc = new SQLDataSetCommand(strSQL, conn);
// populate a dataset with the SQL results
DataSet ds = new DataSet();
dsc.FillDataSet(ds, "Users" );
// check to see if the dataset contains no rows (if it is EOF (i.e.
// contains no rows), then the user is invalid)
if( ds.Tables["Users"].Rows.Count == 0 )
{
Message.Text = "Invalid User Name and Password. Try Again.";
} else {
Message.Text = "Congratulations, " + txtLogin.Text +
"!!! You have successfully signed in.";
}
}
}
}
}
|
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)
{
Message.Text = "Enter Login and Password";
}
|
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!
By Mani Raja
Attachments:
Download the source code in ZIP format
Visit the ASP.NET Article Index!