O'Reilly logo

Visual Basic 2005 Cookbook by Tim Patrick, John Clark Craig

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Visual Basic Programming

Introduction

When Visual Basic 1.0 was introduced in the early 1990s, it greatly simplified Windows application development. Visual Basic 2005continues the tradition by providing a programmer-friendly environment in which you can write powerful desktop, web-based, and mobile applications quickly and easily.

In this introductory chapter you’ll see just how easy it is to write a variety of applications by developing a simple application in three Visual Basic–supported flavors: a desktop application (” Windows Forms”), a console application, and a web-based application (“Web Forms” via ASP.NET).

The three recipes in this chapter are meant to be read as a set. The first recipe, which focuses on Windows Forms, includes additional background information concerning the logic of the application developed in all three recipes. Be sure to read this recipe first.

1.1. Creating a Windows Forms Application

Problem

You want to develop a Windows Forms application that converts between the Fahrenheit, Celsius, and kelvin temperature systems.

Solution

Sample code folder: Chapter 01\Forms Version

Create a Windows Forms application, and add the appropriate controls and logic.

Discussion

Start Visual Studio 2005, and then create a new project. The Start Page includes a link to do this, or you can use the File → New Project menu command. The New Project dialog appears, as shown in Figure 1-1.

Visual Studio’s New Project dialog
Figure 1-1. Visual Studio’s New Project dialog

Each template listed in this dialog starts with the most basic and empty Visual Basic project and adds just enough source code and configuration settings to get you started on the selected application type. You could choose the Blank Solution template and work your way up to the functionality provided through the Windows Application template, but that’s more than we need to accomplish right now.

Select Visual Basic (or the Windows entry under Visual Basic) in the “Project types” field and Windows Application in the Templates field, enter the name of your project in the Name field (let’s call ours “FormConvertTemp”), and click the OK button.

As Visual Studio works behind the scenes to configure the initial project features, let’s take a few minutes to review some high school science. The three temperature systems in this program—Fahrenheit, Celsius, and kelvin—are often used to measure heat in the various scientific disciplines:

  • In the Celsius (or Centigrade) scale, water freezes at 0°C and reaches its boiling point at 100°C. This makes it a pretty simple measurement system, at least where water is concerned. Celsius is used as the common temperature measurement system in most countries.

  • The Fahrenheit system uses the environment of its founder, Gabriel Fahrenheit, as its basis for measurement. 0°F, at the lower end of the 0-to-100 scale, is rumored to be the coldest temperature that Fahrenheit measured near his home one winter. The 100°F mark is based on his own body temperature. This system, used in America and a few other locations, is especially convenient if you are a German scientist with a slight fever.

  • The kelvin system uses the same scale size as the Celsius system, but places 0K at absolute zero, the theoretical temperature at which all super-quantum molecular activity ceases. 0K is equivalent to−273.15°C, and all other temperatures on the kelvin scale are converted to Celsius through a simple adjustment of that same 273.15°value. Kelvin is one of the seven base SI (Système International d’Unités) units of measure and is used in scientific work.

The ability to convert between the different systems is important, not only for international relations, but also for health considerations (“Mom, I’m too sick to go to school today; I have a temperature of 310.15K!”).

By now, Visual Studio should have completed its work and presented you with the initial project form (Figure 1-2).

Your project’s initial form
Figure 1-2. Your project’s initial form

The form you see represents the initial main form of your application. It is part of a project, a collection of files usually tied to a single target, such as an application, a dynamic-link library, or some other output. In Windows Forms projects, the target is an executable file (with an EXE file extension) that contains a compiled .NET application. All of the files in your project are listed in the Solution Explorer, one of the standard tool windows in Visual Studio (Figure 1-3).

The top edge of the Solution Explorer includes a set of toolbar buttons that help you “explore the solution.” The most interesting of these buttons is the second from left, the Show All Files button. Clicking this button toggles the view of files included in your project. Most of the files included in your application are hidden from view by default. Visual Studio does an amazing amount of work behind the scenes, and most of this work is stored in hidden project files. Most of these files contain code automatically generated by Visual Studio as you design your program. A few of these files, such as ApplicationEvents.vb, do contain code that you can update manually, but most of your development time will focus on the files that are always displayed.

The Visual Studio Solution Explorer
Figure 1-3. The Visual Studio Solution Explorer

The main area of the form is its design surface, on which you place (or “draw”) controls. The Toolbox (Figure 1-4) contains the controls that you can add to your form; it’s just one of the many “tool windows” available within Visual Studio. If it’s not already displayed, open the Toolbox now through the View → Toolbox menu command.

Partial view of the Visual Studio Toolbox
Figure 1-4. Partial view of the Visual Studio Toolbox

The selection of controls included in the Toolbox varies based on the active project and window. Beyond the default controls, several third parties offer enhanced controls for use in your projects. Once installed, these controls also appear in the Toolbox.

Each form or control has a default configuration, as determined by the developer of the control. You can alter this configuration by changing the active form’s or control’s properties through the Properties window (Figure 1-5). If it is not already in view, display the Properties window with the View → Properties Window menu command.

Partial view of the Properties window
Figure 1-5. Partial view of the Properties window

The properties for the active item are pretty easy to adjust: select the form or control you want to modify, select a property in the Properties window based on the property name in the left column, and use the mouse or keyboard to modify its value in the right column. Some properties can be expanded into distinct sub-properties using the plus sign (+) to the left of the property name. And while most properties accept simple text values, others have mouse-friendly drop-down editors.

Before adding controls to our form, let’s configure the properties of the form itself. Using the Properties window, set the form’s properties as shown in Table 1-1. This table lists only those properties that deviate from their default settings.

Table 1-1. Application form property changes

Property name

New setting

(Name)

ConvertForm

FormBorderStyle

FixedSingle

MaximizeBox

False

MinimizeBox

False

StartPosition

CenterScreen

Text

Convert Temperatures

Now let’s add the controls to the form. This project will use seven controls:

  • Three RadioButton controls to select the source temperature system

  • Three TextBox controls for entering and displaying temperatures

  • One Button control to initiate the conversion

Use the Toolbox to select and add controls to the form. Add a control either by double-clicking on the control in the Toolbox or by selecting the control in the Toolbox and then “drawing” it on the surface of the form using the mouse. Go ahead and add the three RadioButton controls, three TextBox controls, and one Button control, and arrange them so that your form resembles Figure 1-6. You may also want to resize the form to visually fit the contained controls.

Project form with included controls
Figure 1-6. Project form with included controls

Some of the properties in these controls also need to be adjusted. Use the values in Table 1-2 to guide you through the property updates.

Table 1-2. Custom property settings for each control

Control

Property name

New setting

RadioButton1

(Name)

SourceFahrenheit

 

Checked

True

 

Text

&Fahrenheit

RadioButton2

(Name)

SourceCelsius

 

Text

&Celsius

RadioButton3

(Name)

SourceKelvin

 

Text

&kelvin

TextBox1

(Name)

ValueFahrenheit

TextBox2

(Name)

ValueCelsius

TextBox3

(Name)

ValueKelvin

Button

(Name)

ConvertTemperature

 

Text

Convert

The “&” character added to some of the properties sets the keyboard shortcut for that control so that the user can activate it with the Alt+key keyboard sequence.

There are two more tasks to perform on the form itself before we start writing code, both destined to make the form easier to use. The first is to allow the Enter or Return key to act like a click on the ConvertTemperature button. This is done by setting one of the form’s properties: AcceptButton. Setting this property to the name of a valid control—in this case, the ConvertTemperature button control—enables this keyboard action. Go ahead and set the form’s AcceptButton property now.

The second user-friendly update involves setting the " tab order” of the controls on the form. The Tab key allows the user to move from one form control to another, but the movement may look somewhat random to the user unless you specifically declare the order. To set the tab order, first make sure that the form—and not one of its contained controls—is the active object in the designer window. Then select the View → Tab Order menu command. A small number appears next to each control. To readjust the tab order, click the controls in the order you want them to appear (Figure 1-7). You can also set the tab order by altering the TabIndex property of each control, but the mouse method is generally quicker.

Project form with tab order set for each control
Figure 1-7. Project form with tab order set for each control

When you are finished, select the View → Tab Order menu command once more (or press the Escape key) to return to standard editing.

Now it’s time to program! All of the code for this application will appear in the ConvertTemperature button’s Click event procedure, which you can access by double-clicking on the ConvertTemperature button itself. Visual Studio switches to a code editor with the following event procedure template ready to use:

	Public Class ConvertForm
	   Private Sub ConvertTemperature_Click( _
	         ByVal sender As System.Object, _
	         ByVal e As System.EventArgs) _
	         Handles ConvertTemperature.Click

	   End Sub
	End Class

Add the following code to the Click event procedure body. It determines the source temperature type, checks for valid input, and then performs the conversion:

	' ----- Convert between Fahrenheit, Celsius, and kelvin.
	On Error Resume Next

	If (SourceFahrenheit.Checked = True) Then
	   ' ----- Convert from Fahrenheit to other types.
	   If (IsNumeric(ValueFahrenheit.Text) = True) Then
	      ' ----- F->C, F->K.
	      ValueCelsius.Text = _
	         (Val(ValueFahrenheit.Text) - 32) / 1.8
	      ValueKelvin.Text = _
	         ((Val(ValueFahrenheit.Text) - 32) / 1.8) + 273.15
	   Else
	      ' ----- Invalid data.
	      ValueCelsius.Text = "Error"
	      ValueKelvin.Text = "Error"
	   End If
	ElseIf (SourceCelsius.Checked = True) Then
	   ' ----- Convert from Celsius to other types.
	   If (IsNumeric(ValueCelsius.Text) = True) Then
	      ' ----- C->F, C->K.
	      ValueFahrenheit.Text = _
	         (Val(ValueCelsius.Text) * 1.8) + 32
	      ValueKelvin.Text = Val(ValueCelsius.Text) + 273.15
	   Else
	      ' ----- Invalid data.
	      ValueFahrenheit.Text = "Error"
	      ValueKelvin.Text = "Error"
	   End If
	Else
	   ' ----- Convert from kelvin to other types.
	   If (IsNumeric(ValueKelvin.Text) = True) Then
	      ' ----- K->F, K->C.
	      ValueFahrenheit.Text = _
	         ((Val(ValueKelvin.Text) - 273.15) * 1.8) + 32
	      ValueCelsius.Text = Val(ValueKelvin.Text) - 273.15
	   Else 
	      ' ----- Invalid data.
	      ValueFahrenheit.Text = "Error"
	      ValueCelsius.Text = "Error"
	   End If
	End If

The program is now ready to use in all weather conditions.

Although this program is pure .NET through and through, the only .NET code we witnessed was through the event handler. The call to the ConvertTemperature_ Click event happens indirectly in the code; there is no line of source code, at least in your code, that makes a direct call to the event handler.

When the user clicks on the ConvertTemperature button, the low-level device driver for the mouse inserts mouse-down and mouse-up events into the global Windows input-processing queue. The device driver doesn’t know anything about the various windows displayed on-screen or about .NET; it reports only that a mouse event occurred at a specific X and Y position on the screen. The Windows operating system uses this location to determine which window or control was clicked. Once that’s determined, it sends relevant messages to the message queue of the application that owns the clicked window. The application notifies the clicked control that the user has, in fact, clicked that control. Finally, the code within the .NET control issues a RaiseEvent statement, which triggers a call to the ConvertTemperature_Click event handler.

That’s a lot of steps between your finger and the event handler. Fortunately, you don’t have to handle all of those steps yourself. The relevant logic already exists in Windows and in .NET; you just have to write the event handler and connect it to the specific event through the handler’s Handles keyword (which Visual Basic 2005generates for you):

	Private Sub ConvertTemperature_Click( _
	   ByVal sender As System.Object, _
	   ByVal e As System.EventArgs) _
	   Handles ConvertTemperature.Click

The rest of the code in the application is composed of standard logic and calculations that you might find in code from any programming language: If conditional statements, assignment statements, and expression processing with operators such as the multiplication operator (*).

See Also

The other recipes in this chapter demonstrate how to implement the same program, using different types of interfaces.

1.2. Creating a Console Application

Problem

You want to develop a Console application that converts between the Fahrenheit, Celsius, and kelvin temperature systems.

Solution

Sample code folder: Chapter 01\ Console Version

Create a Windows Console application, and add logic to perform all the calculations based on the user’s input. First, read through Recipe 1.1 for background information on using Visual Studio and on converting between the various temperature systems.

Discussion

Start Visual Studio 2005, and then use the File → New Project menu command to create a new project. Select the Windows project type, and then select the Console Application template. Click OK to create the new project. Since a console application doesn’t have a special user interface, Visual Studio simply displays the default code block for the new project:

	 
Module Module1
	   Sub Main( )

	   End Sub
	End Module

There are a few different ways to rename the module. If you only want to change the name in the code, just replace the word “Module1” with something like “Convert-Temperature”:

	Module ConvertTemperature

Unfortunately, this requires you to make a change to the project’s properties. Before the change, Visual Studio planned to start the program from the Sub Main routine in the Module1 module. But since you changed the name, there is no longer a Module1 for Visual Studio to use.

To modify the properties, select the Project → ConsoleApplication1 Properties menu command, or double-click on the My Project item in the Solution Explorer panel. When the Project Properties window appears, the Application tab in that window should already be active. To change the starting code for the program, select “ConvertTemperature” from the “Startup object” field. Then close the Project Properties window, and return to the code.

If you want to avoid all of this unpleasantness, rename the module’s filename instead of its name in the code. To do this, right-click the Module1.vb file in the Solution Explorer, choose the Rename command from the shortcut menu that appears, and give it a new name such as ConvertTemperature.vb. (Don’t forget the .vb extension.) Visual Studio will change the module name as well and fix up all the other loose connections.

All of the conversion code will go in the Sub Main routine:

	Module ConvertTemperature
	   Sub Main( )
	      ' ----- The program starts here.
	      Dim userInput As String
	      Dim sourceType As String

	      On Error Resume Next

	      ' ----- Display general instructions.
	       
Console.WriteLine("Instructions:" & vbCrLf & _
	         "To convert temperature, enter a starting " & _
	         "temperature, followed" & vbCrLf & _
	         "by one of the following letters:" & vbCrLf & _
	         "  F = Fahrenheit" & vbCrLf & _
	         "  C = Celsius" & vbCrLf & _
	         "  K = kelvin" & vbCrLf & _
	         "Enter a blank line to exit." & vbCrLf)

	      ' ----- The program continues until the user
	      ' enters a blank line.
	      Do While True
	         ' ----- Prompt the user.
	          
Console.WriteLine("Enter a source temperature.")
	         Console.Write("> ")
	         userInput = Console.ReadLine( )

	         ' ----- A blank line exits the application.
	         If (Trim(userInput) = "") Then Exit Do

	         ' ----- Determine the source type.
	         userInput = UCase(userInput)
	         If (InStr(userInput, "F") > 0) Then
	            ' ----- Start with Fahrenheit.
	            sourceType = "F"
	            userInput = Replace(userInput, "F", "")
	         ElseIf (InStr(userInput, "C") > 0) Then
	            ' ----- Start with Celsius.
	            sourceType = "C"
	            userInput = Replace(userInput, "C", "")
	         ElseIf (InStr(userInput, "K") > 0) Then
	            ' ----- Start with kelvin.
	            sourceType = "K"
	            userInput = Replace(userInput, "K", "")
	         Else
	            ' ----- Invalid entry.
	            Console.WriteLine("Invalid input: " & _
	               userInput & vbCrLf)
	            Continue Do
	         End If

	         ' ----- Check for a valid temperature.
	         userInput = Trim(userInput)
	         If (IsNumeric(userInput) = False) Then
	             
Console.WriteLine("Invalid number: " & _
	               userInput & vbCrLf)
	            Continue Do
	         End If

	         ' ----- Time to convert.
	         If (sourceType = "F") Then
	            ' ----- Convert from Fahrenheit to other types.
	             
Console.WriteLine(" Fahrenheit: " & userInput)
	            Console.WriteLine(" Celsius: " & _
	               (Val(userInput) - 32) / 1.8)
	            Console.WriteLine(" kelvin: " & _
	               ((Val(userInput) - 32) / 1.8) + 273.15)
	         ElseIf (sourceType = "C") Then
	            ' ----- Convert from Celsius to other types.
	            Console.WriteLine(" Fahrenheit: " & _
	               (Val(userInput) * 1.8) + 32)
	            Console.WriteLine(" Celsius: " & userInput)
	            Console.WriteLine(" kelvin: " & _
	               Val(userInput) + 273.15)
	         Else
	            ' ----- Convert from kelvin to other types.
	            Console.WriteLine(" Fahrenheit: " & _
	               ((Val(userInput) - 273.15) * 1.8) + 32)
	            Console.WriteLine(" Celsius: " & _
	               Val(userInput) - 273.15)
	            Console.WriteLine(" kelvin: " & userInput)
	         End If
	      Loop
	      End
	   End Sub
	End Module

Running the program opens up a command window. You will immediately be prompted to enter a source temperature. The program continues to convert values until it detects a blank line for input. Here is a typical short session:

	Instructions:
	To convert temperature, enter a starting temperature, followed
	by one of the following letters:
	  F = Fahrenheit
	  C = Celsius
	  K = kelvin
	Enter a blank line to exit.

	Enter a source temperature.
	> 37c
	  Fahrenheit: 98.6
	  Celsius: 37
	  kelvin: 310.15
	Enter a source temperature.
	>

Console applications bring back memories of those pre-Windows days when the 80-by-24-character console display was the primary user interface mechanism on the IBM PC platform. Text input and output, and maybe some simple character-based graphics and color, were all the visual glitz that a programmer could use.

Console applications in .NET use that same basic text-presentation system as their primary interface, but they also include the full power of the .NET libraries. For the actual user interaction, the Console object takes center stage. It includes features that let you display text on the console (Write(), WriteLine()), retrieve user input (Read(), ReadKey(), ReadLine()), and manipulate the console window in other useful ways.

The temperature conversion program uses the Console object and some basic temperature formulas within its core processing loop. First, it gets a line of input from the user and stores it as a string:

	userInput = Console.ReadLine( )

The input must be a valid number, plus the letter F, C, or K. The letter can appear anywhere in the number: 37C is the same as C37 is the same as 3C7. Once the program has extracted the numeric temperature and its source system, it performs the conversion; it then outputs the results using the Console.WriteLine() method.

See Also

The recipes in this chapter should be read together to gain a full understanding of general .NET application development concepts.

1.3. Creating an ASP.NET Web Forms Application

Problem

You want to develop a Web Forms application in ASP.NET that converts between the Fahrenheit, Celsius, and kelvin temperature systems.

Solution

Sample code folder: Chapter 01\Web Version

Create a new Web Forms application, and use ASP.NET development tools and coding methods to craft your application. First, read through Recipe 1.1 for background information on using Visual Studio and on converting between the various temperature systems.

Discussion

Start Visual Studio 2005, and then create a new web site (not a “New Project”). You can use either the Create Web Site link on the Start Page or the File → New Web Site menu command. The New Web Site dialog appears, as shown in Figure 1-8.

Visual Studio’s New Web Site dialog
Figure 1-8. Visual Studio’s New Web Site dialog

Make sure that ASP.NET Web Site is selected in the list of templates, choose File System for the location type, enter the new directory name (or just use the default, although we’re going to use “WebConvertTemp” as the final directory component), naturally select Visual Basic as the programming language, and then click the OK button.

Visual Studio does a little work and then presents you with a blank page. This is a web page document on which you will place your various web display elements. By default, it acts like a word processing document, in which added elements flow left to right, top to bottom. You can opt to place elements at specific locations, but we’ll stick with the default placement mode for this program.

If it’s not already in view, display the Toolbox through the View → Toolbox menu command. No doubt you’ve already seen the Toolbox used in Windows Forms applications. The tools displayed now are similar, although they are for specific use by ASP.NET applications only.

As with Windows Forms applications, Visual Studio presents the user interface to you, secretly writing the code behind the scenes. The generated code in Windows Forms is all Visual Basic code; you can write an entire Windows Forms application in Notepad using only Visual Basic statements. ASP.NET applications use Visual Basic for core logic and “code behind” event handlers, but the user interface is defined through an HTML/XML mix. You can modify this HTML yourself (click on the Source button at the bottom of the web page window to see the HTML generated so far) and have the changes reflected in the user interface.

For this project, let’s take things easy and simply use the Toolbox to add display elements. Make sure you are in Design view (instead of HTML Markup/Source view). Type the following text into the web page document, and then press Enter:

	Convert Temperature

Add the following usage text below this, and press Enter again:

	Select the source temperature system, enter the value,
	and then click the Convert button.

The text is somewhat plain, so let’s do a little formatting. Highlight the word “Convert” in the usage text, and press the Control-B key combination to make the text bold, just as you would in most word processors.

I think the title line would also look better as a heading. Switch into HTML mode by clicking on the Source button at the bottom of the page or selecting the View → Markup menu command. You should see the following HTML code, or something pretty close to it:

	<%@ Page Language="VB" AutoEventWireup="false"
	CodeFile="Default.aspx.vb" Inherits="_Default" %>

	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<html xmlns="http://www.w3.org/1999/xhtml" >
	<head runat="server">
	    <title>Untitled Page</title>
	</head>
	<body>
	    <form id="form1" runat="server">
	    <div>
	        Convert Temperature<br />
	        Select the source temperature system, enter the value,
	        and then click the <strong>Convert</strong>
	        button.<br />

	    </div>
	    </form>
	</body>
	</html>

If you’ve written HTML in the past, this should mostly look familiar. Modify the “Convert Temperature” line to include <h1> (heading level #1) tags around the text, removing the <br> tag:

	<h1>Convert Temperature</h1>

Return to the user interface designer by clicking on the Design button at the bottom of the page or using the View → Designer menu command.

Next, we need to add a selector for the three different temperature systems. To add an instance of the RadioButtonList control to the end of the web page, click at the bottom of the web page and then double-click on the RadioButtonList item in the Toolbox. A default single-item list appears. This list includes a “task pane,” as shown in Figure 1-9 (Visual Studio includes such “smart tags” and task panes for many user interface elements). Click on the Edit Items link in this pop up.

Convenient features for user interface elements
Figure 1-9. Convenient features for user interface elements

Use the ListItem Collection Editor that appears to add each temperature system. Table 1-3 contains the data you need to enter your selections. When you are done, close the ListItem Collection Editor window.

Table 1-3. Radio button list items

Member

Text

Value

0

Fahrenheit

F

1

Celsius

C

2

kelvin

K

Since we’ll be interacting with this radio button list in code, we need to give it a meaningful name. In the Properties window, set the (ID) property to “SourceType.”

Back in the web page designer, start a new line with the text “From Temperature:” and follow it with a TextBox control from the Toolbox. Name the control (that is, set its (ID) field to) “SourceValue.”

On yet another line, add a Button control, name it “ConvertNow,” and set its Text property to “Convert.” A click on this button is destined to generate the converted temperatures.

That’s it for the data-entry portion, though we still need a place to display the results. We’ll use a simple table presentation. First, set off the results visibly by adding a Horizontal Rule control. This is actually a standard HTML element, so you’ll find it in the HTML section of the Toolbox. After that, add a title that reads “Temperature Results” (add the <h1> tags if you wish).

Now add a table through the Layout → Insert Table menu command. When the Insert Table form (Figure 1-10) prompts you for a table size, specify three rows and two columns, and then click OK. When the table appears, enter the names of the three temperature systems in the left-most cells: Fahrenheit, Celsius, and kelvin.

Inserting a new table on a web page
Figure 1-10. Inserting a new table on a web page

ASP.NET table cells can include names, and we will use such names to update the right-most cells with converted temperature data. As you click in each right-column cell, the Properties window displays the details for each related <td> element. Add an ASP Label control to each of the fields in the right column of the table, and then edit the (ID) property of each cell to use the following cell names, from top to bottom: “ResultFahrenheit,” “ResultCelsius,” and “ResultKelvin.”

Let’s make one final change to the presentation. In Visual Studio’s Properties window, select DOCUMENT from the list of objects at the top of the panel. Modify the Title property, which currently contains “Untitled Page,” to read “Convert Temperature” instead. This is the title that appears in the browser’s titlebar when running the application.

That’s it for the user interface design. You should now have a web-page display similar to Figure 1-11.

A beautiful ASP.NET Web Forms application
Figure 1-11. A beautiful ASP.NET Web Forms application

Let’s move on to the source code. Visual Studio has generated all of the HTML markup on our behalf, but we need to supply the temperature conversion logic. Click on the View Code button in the Solution Explorer, or select the View → Code menu command. Although it’s not much, Visual Studio wrote a little bit of this code, too:

	Partial Class _Default
	   Inherits System.Web.UI.Page

	End Class

The only code we need to add is the event handler for the Convert button that performs the actual conversion. Add this code to the project. You can double-click on the Convert button in the designer to have Visual Studio add the event handler template:

	Protected Sub ConvertNow_Click(ByVal sender As Object, _
	      ByVal e As System.EventArgs) Handles ConvertNow.Click
	   ' ----- The conversion occurs here.
	   Dim origValue As Double

	   If (IsNumeric(SourceValue.Text) = True) Then
	      ' ----- The user supplied a number. Convert it.
	      origValue = CDbl(SourceValue.Text)
	      If (SourceType.SelectedValue = "F") Then
	         ' ----- From Fahrenheit.
	         ResultFahrenheit.Text = CStr(origValue)
	         ResultCelsius.Text = CStr((origValue - 32) / 1.8)
	         ResultKelvin.Text = CStr(((origValue - 32) / 1.8) + _
	            273.15)
	      ElseIf (SourceType.SelectedValue = "C") Then
	         ' ----- From Celsius.
	         ResultFahrenheit.Text = CStr((origValue * 1.8) + 32)
	         ResultCelsius.Text = CStr(origValue)
	         ResultKelvin.Text = CStr(origValue + 273.15)
	      Else
	         ' ----- From kelvin.
	         ResultFahrenheit.Text = CStr(((origValue - 273.15) * _
	            1.8) + 32)
	         ResultCelsius.Text = CStr(origValue - 273.15)
	         ResultKelvin.Text = CStr(origValue)
	      End If
	   Else
	      ' ----- Unknown source value.
	      ResultFahrenheit.Text = "???"
	      ResultCelsius.Text = "???"
	      ResultKelvin.Text = "???"
	   End If
	End Sub

If you’ve already read the other recipes in this chapter, this code should look some-what familiar. It simply applies the standard temperature-conversion formulas to the source number based on the type of source temperature selected, then puts the results in the output display fields.

Tip

When you run this recipe, it properly converts temperatures but only when you click on the Convert button directly. If you’re like us, you want to reduce the number of keystrokes and mouse clicks you need to use in any program. The program doesn’t convert properly if you simply hit the Enter key from the source temperature field, SourceValue. ASP.NET has a way to change this behavior. Add this event handler to your application to enable conversion via the Enter key (or add the RegisterHiddenField() statement to your Page_Load event if you already have that handler).

	Protected Sub Page_Load(ByVal sender As Object, _
	     ByVal e As System.EventArgs) Handles Me.Load
	  ClientScript.RegisterHiddenField("_ _EVENTTARGET", _
	     "ConvertNow")
	End Sub

It’s hard to read, but there are two underscore characters before “EVENTTARGET.”

The code you use to develop ASP.NET applications is not exactly the same as the code you use for desktop applications, but it’s close. Event handlers in ASP.NET look like event handlers in Windows Forms applications, although the timing of the events is a little different. Functions that exist for calculation purposes only and that have no direct interaction with the user or the user interface may be moved freely between Windows Forms and Web Forms applications, but some of the code is very much tied to the ASP.NET programming model. Still, that’s what you would expect given that half of a Web Forms application’s user-interface code is written in HTML instead of Visual Basic.

The HTML code that is included is a little nonstandard. Take a look at the HTML markup associated with the application (select View → Markup when the designer is in view). Although there are the standard <body> and <table> tags throughout the page, there are also some tags that begin with asp:, as in <asp:RadioButtonList>. Each tag represents a Web Forms Server Control and is directly tied to a .NET Framework–coded class (a class you can instantiate and manipulate just like any other .NET class). The RadioButtonList class, for instance, is found in the System.Web.UI.WebControls namespace, along with most of the other ASP.NET-specific controls.

When ASP.NET processes a web page with these embedded web controls, the control class emits standard HTML code in place of the <asp:RadioButtonList> tag set.

Fortunately, you don’t need to know how the internals of these classes work or exactly what kind of HTML they emit. You can simply add the controls to your web page using drag-and-drop, and interact with each control through its events and properties. And that’s what we did here. We added a couple of controls to a form, adjusted their properties, and then responded to a single event. These actions resulted in a complete web-based application. ASP.NET even adjusts the emitted HTML for the user based on the flavor of the browser being used.

See Also

The recipes in this chapter should be read together to gain a full understanding of general .NET application development concepts.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required