Channel Insider content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Bigger projects often benefit by being modularized, and .NET gives you more ways to do this than does ASP. You could do a fairly good job modularizing an ASP application with subroutines, functions, and includes, but at some point you’ll find yourself forced to mix the server side code with HTML code. While mixed code like this really isn’t that bad, and it does work, it’s hard to understand. Usually, only the authoring coder understands the code enough to make any significant changes quickly.

The .NET languages introduced server controls, which allow you to completely separate the HTML from the server side code. Server controls use reserved tags to identify themselves, much as tags in HTML or XML do. Once the .NET compiler processes one of these reserved tags, it calls upon and executes other code from the language library for the control.

Does this sound a lot like some sort of preset fancy include files? You wouldn’t be wrong in thinking of server controls this way. They make life easier. It’s a snap to add a Calendar, Banner Add Rotator, and other items to your code. You can even create your own controls, called user controls; they function the same as server controls, but it’s your own code rather than Microsoft’s or a third-party vendor’s. You can add user controls to any project you are working on, just like you would the .NET server controls.

In this article, I show you one example control, called a login user control. It’ll introduce you to user controls, and you’ll learn how they can simplify and speed up your development time, just as server controls do. Oh yeah. It’ll also be useful in your applications. Nice, huh?

Creating the Login User Control

All user control code must reside in a file with an .ascx extension, which tells the .NET compiler that the code in this file type is a user control. This starts out ver easily: to create the control, code the page the same way you would a script (aspx) page. At the top of the page, include the following directives for the login user control:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Control Language="C#" EnableViewState="False" %>

The third directive is reserved for a user control, and is only used in ascx pages. It tells the compiler that this is a user control (ascx page) and disables the view state across pages (also known as session state). There are a number of other attributes that you can use with this directive, but I won’t get into them in this article as they are not used that often.

Now for the section of the script code that I like to call the interface and implementation. The interface contains the server controls for the login and password text boxes, and the implementation contains the code that is executed when the Submit button is clicked.

The Interface

What we need for this part of the code is four server controls: two for the text boxes, one for the Submit button, and one for the form. The only other code included is some simple HTML code for formatting purposes. The code for the interface appears below in Listing 1:

Listing 1: Code for the Interface

1 <form runat="server">
2 <table align="center">
3 <tr><td colspan="2"> </td></tr>
4 <tr>
5 <td align="right">Login</td>
6 <td><asp:TextBox id="Login" Text=" Width="75px" runat="server"/></td>
7 </tr>
8 <tr>
9 <td align="right">Pass</td>
10 <td><asp:TextBox id="Pass"
  TextMode="password" Text=" Width="75px" runat="server"/></td>
11 </tr>
12  <tr>
13  <td colspan="2"> </td></tr>
14 <td align="center" colspan="2"><input type=submit value='Login" 
  OnServerClick="Button_Login" runat="server"></td>
15 </tr>
16 </table>
17 </form>

When executed, the code shows the screen in Figure 1. It is a nice simple login form, that can be jazzed up all you like.

All the code must reside between the form tags (lines 1 and 17), along with the runat=server attribute. This tells the compiler that code inside the form has server controls. Lines 6 and 10 contain the text box user controls, and line 14 contains the button server control that execute a function called Button_Login after being clicked by the user to login. The code for Button_Login resides in the implementation portion of the user control, as you’ll see later.

The Implementation

The implementation is almost as easy. All we need to do is set up a database connection and traverse the recordset for a login and password match. The Button_Login function gets the user input data from the server text box controls, and makes the comparisons. If a match is found, the user is routed to the application’s main page; if the user credentials are not found, it keeps him at the login page.

The code for the interface section appears below in Listing 2:

Listing 2: Code for the implementation

1 <script language="C#" runat="server">

2 void Button_Login(object Source, EventArgs e) {

3	int lgflg = 0;

4	SqlConnection conn =
  new SqlConnection( ConfigurationSettings.AppSettings["DSN"].ToString() );	
5	SqlCommand  cmd =
         new SqlCommand("SELECT ID From [User_tbl] Where Pass = '" + Pass.Text 
         + "' And Login = '" + Login.Text + "'",conn); 	  

6	conn.Open();
7	     SqlDataReader myReader = cmd.ExecuteReader();

8	     while (myReader.Read())
9	     {
10		lgflg = 1;
11	     }
12	     myReader.Close();	
13	conn.Close();  

14	if (lgflg == 1) {
15		Response.Redirect("default.aspx");
16	}

17 }
18 </script>

Lines 1 and 18 define the code block for the C# script that handles data returned by the server controls in the interface. This block contains the functions that do all the work.

Lines 2-18 are the Button_Login function. Inside this function we set up a database connection (on line 4) using the web.config file for the application. You don’t have to do it this way, but it is convenient. Line 5 contains the SQL call to the user table that holds the user login and password data. Line 3 defines an integer flag that is toggled on if a record is found (line 10).

Line 14-16 checks to see if the flag is on. If it is, the user is routed to the default page for the application. If it isn’t toggled on, the user stays at the login page until he enters the correct credentials.

You may be asking why I don’t just route the user to the default page, right there on line 10, instead of using a flag and making an extra comparison down below. The reason for this is that we want to get out of the while loop and close the connection on line 13 before leaving the control (or the .aspx page that contains it). If we route them from inside the while loop, the connection will remain open but be no longer used. That consumes unnecessary memory and system resources.

This concludes the code for the user control. Save this page as anything you like. I called it userlogin.ascx. Next, let’s see how to tie this control to a script page.

Registering the User Control with a Script Page

The last part of the process is the simplest. Let’s say you want to include this user control in a script page, called login.aspx. To do this, the only code you need for this script page is a simple directive and the user control (see Listing 3 below).

Listing 3: Tying the control to a script page

<%@ Page Language="C#" runat="server" %>  
<%@ Register TagPrefix="UserControl" TagName="UserLogin" Src="userlogin.ascx" %> 

   <UserControl:UserLogin runat="server" />

Was that easy or what? All we had to do is register the control with the @Register directive on line 2, telling the compiler the name that is used to reference this control (TagName) and the file containing the source code for the control (userlogin.ascx). The TagPrefix — in this example UserControl — defines the tags that are used to reference the control (Line 3).

I think it’s neat how you can define your own tags, and the .NET compiler will know what they are every time any code containing them is compiled. It really makes it flexible and keeps the code neat looking and easy to understand. If you modularized all your code with user controls, you would end up with an easy-to-manage flexible application. This is why user controls are also good for Web site templates as well.

If you run the code in Listing 3, you’ll get the page shown in Figure 1. It will function and do everything it needs to, such as verifying the login and password and routing the user to the applications default page when authenticated. You can use the control with any of your applications with little or no coding, thus speeding up development time.

In this article you learned how to set up your own login user control to use with Web applications that require user permissions. I would encourage you to create using user controls to modularize your applications to make them more manageable. I personally have found them very useful; I create more controls all the time, adding them to my user control library. Many development companies are creating user controls for programmers to download and use. You can find them in control galleries all over the Web, so if there is one you don’t have time to create, see if one available serves your purpose.