Getting Started with ASP.NET

Getting Started with ASP.NET

efore we can dive in and begin building Web pages with ASP.NET, I want to introduce a few topics and new terminology.

.NET Framework
Microsoft designed classes in the .NET Framework to accommodate your current programming needs and beyond. It contains classes for many activities including manipulating text, working with database data, and working with the file system. The .NET Framework also contains classes that represent the basic data types including integers, bytes, strings, and arrays. You should learn one of the .NET languages, but it is vital that you learn about the .NET Framework. Do you have to know how to use every class in the Framework before you can become an effective .NET developer? No, but there are quite a few classes you need to learn about before you will make any substantial headway. When it comes to developing in .NET, the Framework is everything.

Fast Facts
ASP.NET is actually built into the .NET Framework. You technically don’t even need Visual Studio .NET to write ASP.NET code.

Interesting Fact #1: For more information about programming languages supported in .NET see the CoDe Magazine Sep/Oct 2002 issue.

As you can probably imagine, the entire .NET Framework is huge. It is comprised of thousands of classes, or as astronomer Carl Sagan might say, “billions and billions!” Management and classification of this enormous list of classes requires an organizational mechanism. The organizational mechanism that manages the .NET Framework is called a namespace. Simply put, a namespace is a logical grouping of classes. For example, the System.Web namespace stores all of the classes that relate to working with browser-server communication.

The .NET Framework organizes namespaces into a hierarchical tree structure. The System namespace resides at the root of this tree. It contains all of the classes for working with the base data types, random numbers, dates, directories, and other system resources.

To uniquely identify a class in the .NET Framework, you reference the class by its full namespace and class name. For example, to refer to the File class contained in the System.IO namespace you would use:


Table 1 shows a partial list of standard namespaces.

Table 1: Partial list of standard namespaces.




The root namespace for the entire .NET Framework. Contains the base types and other useful classes.


Contains classes for working with the standard collection types.


Contains classes for working with Web configuration files (web.config).


Contains classes for interaction with data sources (ADO.NET).


Contains classes for accessing Active Directory Services.


Contains classes for reading and writing files.


Contains classes for working with strings.


Contains classes that process XML data.

.NET Languages
.NET supports a number of languages. By default, Visual Studio .NET installs Visual C# .NET (usually abbreviated as C# and pronounced c-sharp), Visual Basic .NET, and Visual C++ .NET. The two languages most commonly used in .NET are Visual Basic .NET and C#. Other languages that have been ported over to .NET include COBOL, Eiffel, and PERL. I’ll use Visual Basic .NET throughout this article.

File Extensions
As is the case with just about every new development environment, you’re going to need to be aware of a few new file extensions in Visual Studio .NET.

Table 2 lists common file extensions that ASP.NET uses.

Table 2: Common ASP.NET file extensions.




ASP.NET page file


ASP.NET User Control file


Web service file


Visual Basic .NET code file for an ASP.NET page


C# code file for an ASP.NET page


Visual Studio .NET Solution file

Set Up and Installation
In order to run ASP.NET Web Forms you need to have Internet Information Server (IIS) and the .NET Framework Software Development Kit (SDK) installed on your machine (installing IIS is beyond the scope of this article).

Notice I didn’t say you need Visual Studio .NET installed on your machine to build and run ASP.NET Web Forms. Just like standard HTML, you can create your ASP.NET Web Forms in any text editor. However, we’ll use Visual Studio .NET as the development environment.

Your First ASP.NET Project
Now you’re ready to get your feet wet. Launch Visual Studio .NET and let’s get started.

To create a new ASP.NET project in the Visual Studio .NET IDE, select File | New | Project, and then select ASP.NET Web Application from the Templates. Name the project LearnASPNet (see Figure 1), click OK, and Visual Studio will build the project files. The Solution Explorer will contain your newly created project and a Web Form named Webform1.aspx (see Figure 2).

Figure 1: Create new projects in Visual Studio .NET using the New Project dialog box. There is a template for each type of .NET application.
Figure 2: The Solution Explorer contains all of the items referenced in the application.

The first thing to do is rename Webform1.aspx to MyFirstWebForm.aspx. Right-click on Webform1.aspx and select Rename. Then, right-click on MyFirstWebForm.aspx again and select Set As Start Page. This ensures that MyFirstWebForm.aspx will be the Web Form initially displayed when you run the project.

Let’s launch this Web Form just to make sure you configured your machine correctly. Click the blue triangle in the toolbar (see Figure 3), select Debug | Start, or press F5 to launch the form.

Figure 3: The Visual Studio .NET toolbar provides a convenient way to open and save projects, cut, copy, and paste elements, and run your projects.
See also  Comparing different methods of testing your Infrastructure-as-Code

If you set up your machine correctly you should see a blank Web page (see Figure 4). Congratulations, you’ve just created and run your first ASP.NET Web Form! Close the browser and return it to the Visual Studio .NET IDE.

Figure 4: Running the project also compiles the project and launches the browser loaded with the start page, MyFirstWebForm.aspx.

One of the first things to note about your newly-created Web page is the text in the middle regarding the layout mode of the page. There are two options for layout mode: GridLayout and FlowLayout. You specify the layout mode used by the page on the General tab of the DOCUMENT Property Pages dialog box. Right-click on the page and select Properties to display the DOCUMENT Property Pages dialog box (see Figure 5).

Interesting Fact #2: VB.NET supports declaring a variable and assigning a value to it on the same line, for example: Dim intCounter As Integer = 10.

You’re probably wondering, what’s the difference between the two layout modes? GridLayout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, FlowLayout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers.

Figure 5: Use the DOCUMENT Property Pages dialog box to configure settings of a page. Commonly used settings include Page title, Default scripting language, Page Layout, and Keywords.

Which layout should you use? Flowlayout is the safer route, however, absolute positioning is appropriate for an intranet application when you are sure all of your users will have a compatible browser.

While you still have the Property Pages dialog box open, go ahead and change the Page Title to My First Web Form. Click OK to close the dialog box.

Adding Controls
We will examine a few controls shortly, but first you need to learn how to add a control to a form. The Toolbox is located on the left side of the screen. Select the Web Forms controls section and double-click the TextBox control. You should now see a text box on your Web Form. Right-click the text box and select Properties from the shortcut menu. Change the ID property to txtName (see Figure 6). Next, add a button control. Name the button cmdSubmit and set its Text property to Away I Go!

Interesting Fact #3: ASP.NET knows the capability of each browser. Using a feature called down-level support, it sends the appropriate HTML to the user’s browser.
ASP.NET Controls
When you create an ASP.NET page, you have the option of using four different types of controls. You can use the HTML Controls, which are server-side versions of the standard HTML tags; you can use the Web Controls, which are a more flexible and object-oriented set of controls; you can use the Validation Controls, which provide automatic data validation; and you can use User Controls, which are developer-created controls.

Although you can use a combination of standard HTML tags and Web Controls, HTML gets sent back to the client’s browser. Microsoft designed the ASP.NET controls to help make creating Web pages less complicated than using traditional ASP, but in the end, the page sends standard HTML to the client’s browser.

HTML Controls
HTML controls are contained in the System.Web.UI.HTMLControls namespace, and provide a convenient path for migrating existing code to ASP.NET. See Figure 7 for the list of HTML Controls found in the HTML section of the Toolbox in Visual Studio .NET. The HTML controls provide a simple way to convert an existing ASP page to an ASP.NET page. One key property setting is runat=”server”. This article focuses on the more flexible and powerful Web Controls.

Interesting Fact #4: The .NET Framework Software Development Kit (SDK) is installed as part of the Visual Studio .NET installation.
Button and ImageButton Controls
When clicked, both Button and ImageButton controls submit the form that contains them to the Web server. What’s the difference between these two types of button controls?

The Button control renders the same HTML as the tag and displays on a page as a gray button. Table 8 lists Button control properties, methods, and events.

Table 8: Button control properties, methods, and events.




Passes this value to the Command event when the button is clicked.


Passes this value to the Command event when the button is clicked.


Specifies if the button causes the form validation controls to validate the entries on the form.


Specifies the text displayed on the button.




Raises the Click event.


Raises the Command Event.




Raised when the button is clicked. The form containing the button is submitted to the Web server.


Raised when the button is clicked. The values in the CommandName and CommandArgument properties are passed.

Clicking a button submits the form containing the button to the Web server and raises both the Click and Command events. The only difference between these events is that the Command event is passed two additional properties: CommandName and CommandArgument.

Interesting Fact #5: ASP.NET is very picky about closing tags, such as

or . If you don’t need to place anything between the tags you can save typing by closing the tag with />, for example, .

To handle the Click event of a button you could code a subroutine like the following:

   Private Sub cmdSubmit_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles cmdSubmit.Click         Me.cmdSubmit.Text = "Now you don't!"   End Sub

The following code displays a text box, txtDisplay, and three buttons, cmdMultiple, cmdAdd, and cmdSubtract. Notice that each of the buttons has values specified for the CommandName and CommandArgument properties:


The following code handles the Command event raised by clicking the cmdAdd, cmdSubtract, or cmdMultiply command buttons:

   Private Sub PerformCalculation( _      ByVal sender As Object, _      ByVal e As _      System.Web.UI.WebControls.CommandEventArgs) _      Handles cmdAdd.Command, _         cmdSubtract.Command, _         cmdMultiply.Command      Dim intNumber As Integer = _         e.CommandArgument      If e.CommandName = "Add" Then         Me.txtDisplay.Text += intNumber      ElseIf e.CommandName = "Subtract" Then         Me.txtDisplay.Text -= intNumber      ElseIf e.CommandName = "Multiply" Then         Me.txtDisplay.Text *= intNumber      End If   End Sub

Passing the “e” parameter in as the type CommandEventArgs makes the CommandName and CommandArgument properties for the clicked button available to the subroutine. The PerformCalculation example demonstrates how easy it is to build a single routine to handle events for related controls.

The ImageButton control is very similar to the Button control. The main difference between the controls is that you can use the ImageButton control to display an image instead of a plain button. Table 9 lists ImageButton control properties, methods, and events.

Table 9: ImageButton control properties, methods, and events.




Text displayed when the browser does not support images.


Passes this value to the Command event when the button is clicked.


Passes this value to the Command event when the button is clicked.


Specifies if the button causes the form validation controls to validate the entries on the form.


Specifies the positioning of the image. Options include AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right, TextTop, and Top.


Specifies the URL of the image to display for the button.




Raises the Click event.


Raises the Command Event.




Raised when the button is clicked. The form containing the button is submitted to the Web server.


Raised when the button is clicked. The values in the CommandName and CommandArgument properties are passed.

The following HTML code segment creates an ImageButton named ibtnCool that displays the button.gif image:


What are some uses for an ImageButton control? One thing you can use an ImageButton control for is to make a toolbar. You can use a single image for a toolbar containing all the button images you need. In the Click event you can check the value of the X coordinate of the control to determine which button was pressed.

    Private Sub ibtnCool_Click( _      ByVal sender As Object, _      ByVal e As ImageClickEventArgs) _      Handles ibtnCool.Click      Select Case e.X         Case Is < 40            'Corresponds to the position            'of the Add button         Case Is < 150            'Corresponds to the position            'of the Save button         Case Is < 300            'Corresponds to the position            'of the Delete button      End Select

In this article I'm just covering a few of the available Web controls. Additional Web controls you can use include Checkbox, CheckboxList, DataGrid, DataList, DropDownList, HyperLink, ListBox, Panel, PlaceHolder, RadioButton, and RadioButtonList.

Form Field Validation
While it's not one of the most glamorous programming tasks, validating user entries certainly is one of the most important. Unfortunately, it can also be quite time consuming. Microsoft recognized this and created an entire series of Web controls dedicated to making validation quicker and easier.

Interesting Fact #6: You can find out more about creating Regular Expressions and view additional examples in the Visual Studio .NET Help.

The Validation Server controls provide a number of validation capabilities. These capabilities include checking for required entries, ensuring entries match a specified input expression (a telephone number for example), ensuring an entry is within a specified range of values, and ensuring an entry is valid compared to a constant, another control's value, or a database value. Table 10 lists type of validation controls.

Table 10: Validation control types.




Used to make sure a control is not left blank.


Used to compare a user entry to a constant value, another control's property, or a value retrieved from a database.


Used to make sure a user entry is within a specified upper and lower boundary.


Used to make sure an entry matches a pattern defined by an expression.


Used to display any error messages generated by the validation controls on a page.

A validation control acts as a virtual big brother for another server control. Each validation control has a specific job to do for the control it's assigned to watch over. You can assign multiple validation controls to watch a single data entry control. For example, you can assign both a RequiredFieldValidator and a RegularExpressionValidator to watch over the same telephone number TextBox control.

There are three properties that are common to all validation controls: ControlToValidate, ErrorMessage, and Display. The ControlToValidate property specifies which control to watch over. The ErrorMessage property specifies the text to display if the validation fails. The Display property determines where to display the error message.

A validation control is invisible to the user unless it is displaying its error message text. The three settings for the Display property, Static, Dynamic, and None specify how and where to display the error message text. The default value, Static, causes the validation control to take up space even when the error message text is not displayed. This allows you to define a fixed layout for a page. Using the Dynamic setting, validation controls do not take up any space until the error message is displayed. This causes the layout of the page to change when the controls display their message text. The last value, None, is used in conjunction with the ValidationSummary control and suppresses the display of the error message in the validation control. You'll learn more about this setting when we cover the ValidationSummary control.

The Page.Validate method causes the validation controls to work their magic. You can call this method in one of two ways. You can manually call the method or you can set a button's CausesValidation property to True. If the validation fails, your application will display the text specified in the ErrorMessage for the validation controls that failed. With either method, checking the Page.IsValid property in the submitting button tells you if the entries passed the rules set by their validation controls.

The following code shows a button that has its CauseValidation set to True:

   Private Sub btnExample_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles btnExample.Click      'Page.Validate() ? Call if       ' CausesValidation property is set to False      If Page.IsValid Then         'Code here if validation passes      End If   End Sub

Checking the Page.IsValid property allows you to determine if the page validation succeeded or failed. If all entries are valid, the Page.IsValid returns True, otherwise it returns False.

Now we'll take a look at how to use each of the validation controls.

You can use the RequiredFieldValidator control to guarantee that a user doesn't leave an empty control. As with all of the validation controls, you must specify which control the RequiredFieldValidator watches over.

The following HTML code shows a text box named txtPhone with reqPhone, a RequiredFieldValidator control watching over it:


Figure 11 shows the same RequiredFieldValidator control set up in the Property window.

You can use the RegularExpressionValidator control to verify that the entry in a control conforms to a specified Regular Expression. This allows you to check an entry against a pattern such as a U.S. Social Security number, telephone number, email address, etc.

The following HTML code adds a RegularExpressionValidator named regPhoneNumber to watch over the txtPhone text box, which is also watched over by reqPhone, the RequiredFieldValidator:


Figure 13 shows the Property window for the regPhoneNumber RegularExpressionValidator control.

User Controls
User controls, a wonderful feature in ASP.NET, let you bundle multiple UI elements into a single control and place it on a Web Form. If you are familiar with server-side include files, you already have an idea of what I'm talking about. Typical uses of a user control might include a page header or page footer used on multiple pages.

Interesting Fact #7: For more information about User Controls see ASP.NET: Extending the Power of Web Pages with User Controls in the Sep/Oct 2002 issue of CoDe Magazine.

Working with Style Sheets
You can use style sheets to apply formatting characteristics to your Web page content. Style sheets let you make site-wide formatting changes quickly and easily. The concept is simple; you create a file named styles.css, for example, which contains HTML formatting tags and specifies how you want to display your Web page content. For example, suppose you want to make all H3 commands Arial font. Or, suppose you want to make all paragraph commands indent a half-inch. You can even specify the distance you want between lines. You get the idea.

Interesting Fact #8: For additional information on the Visual Studio .NET IDE, check out

20 Cool Visual Studio .NET IDE Features by Markus Egger in the CoDe Magazine March/April 2002 issue.

When you create a new ASP Web Project, ASP.NET automatically creates a Styles.css to use in the project. You can use this style sheet, copy an existing Styles.css file over the one automatically created, or you can use a style sheet of a different name altogether. If you decide to go with a style sheet with a name other than Styles.css, you need to add it to the project by right-clicking the project, selecting Add, and then selecting Add Existing Item.

This example shows a new characteristic named mainheading that I added to the styles.css stylesheet:

   .mainheading    {         font-family: Verdana, Helvetica, sans-serif;        font-size: 14pt;        font-weight: bold   }

In order for a page to adhere to the formatting options in a style sheet, you need to reference the style sheet in the page containing the controls that you want to format. You can do this by dragging and dropping the style sheet from the project onto the page, or by adding the following LINK code to the section of the HTML page:


Once you've linked your style sheet to the page you can begin applying the formatting styles to controls on the page by setting the CssClass property (see Figure 22).


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist

©2024 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.