Home

Variables and Data Types

 

Variables

 

Introduction

A web page whose main purpose is to display regular text and images to the browser is suited for HTML tags only. To make the page more interesting, you and your users can exchange information, as illustrated in the previous lesson. For example, you may want your users to submit values to the server, let the server either store those values or analyze them and send some results to the user. This interact usually means that, in the beginning, you would not know the type of value(s) that one visitor would submit as opposed to another user. Based of this, you must prepare storage areas on the server's computer memory to temporarily hold the values used during a visitor's interaction with your web page. This type of storage area is called a variable.

As there are different types of values used in an application, there are also different requirements to store those values. Fortunately, to store a value in a memory, you must provide only two pieces of information: the name of the variable and the type of information that would be stored in the memory reserved for that variable.

The Name of a Variable

To specify the name of a variable, there are rules you must follow:

  • The name of a variable must start with either a letter or an underscore. A name can have only one letter but if you start it with an underscore, then the underscore must be followed by a letter
  • After the first character as an underscore or a letter, the name can contain letters, digits, or underscores in any combination
  • The name must not contain space but it can be made of various words as long as these words are concatenated (added together to produce one word)
  • The name must not contain any symbol other than letters, digits, or underscores 

After respecting these rules, you can adopt a naming convention that suits you.

 

Data Types

 

Introduction

The values stored in the computer memory depend by their types. For example, one value may be made of only one character. Another value can consist of a natural number. Yet another value can be a long group of characters. When you want to store a value in memory, you must specify how must space that value would need. This is equivalent to declaring the variable. In C#, you must use the following formula:

DataType VariableName;

In Microsoft Visual Basic, to declare a variable, you use the following formula:

Dim VariableName As WhatType

In MSVB, the Dim and the As keywords as required (they were not required in ASP because they are not required in VBScript). The variable name follows the rules we reviewed above. The data type can be one of those we will review.

 

Visual Basic and Value Conversion

When the user types a value in a control (as examples illustrated in the previous lesson), that value is primarily considered a word or a simple group of characters. Before involving that value in an operation, you should first make sure that the value is appropriate for the operation. To support this, Microsoft Visual Basic provides an appropriate function to convert a value from a word to an appropriate value of your choice. The functions used to perform conversions start with C and we will review each for each data type.

 

Characters and Strings

 

Characters

A character is a symbol represented alone. Examples of characters are alphabetical such as a, G, or p. In computer programming, a character can also be a non-readable symbol such as #, &, or [.

To declare a character variable, specify the data type as char. This would be done as follows:

Dim letter As Char

After declaring the variable, you can store a value in the memory that was reserved (allocated) for it. To do this, you can use the assignment operator "=" followed by the desired character in single-quotes (C#) or double-quotes (VB). Here is an example:

letter = 'P'

At any time, you can access the value stored in memory by using the name of its variable. For example, you can display it in the browser by passing its name to the Response.Write() method. Here is an example:

<%@ Page Language="VB" %>
<html>
<head>
<title>ASP.NET Tutorials</title>
</head>
<body>
<h1>Lesson 4: Variables and Data Types</h1>

<p><b>Lecturer:</b> Benjamin Jacobson</b>
<br>
<b>Time Allocated:</b> 74 minutes</p>

<p>This lesson introduces the use of the computer memory to store some 
values that would be used while a visitor is interacting with a web page.</p>

<% Dim letter As Char = "P"
       Response.Write(letter) %>
<h3>Enjoy</h3>
</body>
</html>

This would produce:

If the user provides a value that must be characters, before using it, you may need to convert the value firs into a character. To convert a value to a character, you can use the CChar() function. In the parentheses of this function, type a double-quoted string.

In some cases, you may have a small natural number and you want its equivalent character. To convert a number to a character, use either the Chr() or the ChrW() functions. To proceed, you can write an integer in the parentheses of this function.

 

Strings

A string is an empty space, a character, or a group of characters. When you present a control to the user who is supposed to type in it, the value that the user enters is primarily a string, even if you requested a character or a number. To declare a variable that would hold a string, use the String data type. This would be done as follows:

Dim Something As String

To initialize the string, you can pass a double-quoted value to it. Here is an example:

<% Dim Country As String = "Argentina"
       Response.Write(Country) %>

To convert a value or an expression into a string, you can use the CStr() function. To use it, pass the value or the expression in the parentheses of this function.

 

Practical Learning: Using Strings

  1. Start Microsoft Visual Web Developer and create a new Visual Basic ASP.NET Web Application named cdpub2
  2. To create a new file, on the main menu, click Project -> Add HTML Page...
  3. In the Add New Item dialog box, change the name of the file to ordersummary.aspx
  4. Click Open
  5. Right-click the file and click View HTML Source
  6. Click the first empty line just under the <body> tag and type the following:
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    	<head>
    		<title>members</title>
    		<meta name="vs_defaultClientScript" content="JavaScript">
    		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    		<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    		<meta name="ProgId" content="VisualStudio.HTML">
    		<meta name="Originator" content="Microsoft Visual Studio .NET 7.1">
    	</head>
    	<body MS_POSITIONING="GridLayout">
    <h1>CD Publisher</h1>
    <h2>Order Summary</h2>
    <% Dim strFirstName As String
           Dim strLastName  As String
           Dim strFullName As String
    
           strFirstName = Request.Form("txtFirstName")
           strLastName  = Request.Form("txtLastName")
           strFullName  = strLastName + ", " + strFirstName
           Response.Write("Customer Name: " + strFullName) %>
    
    	</body>
    </html>
    
  7. In the Solution Explorer, right-click WebForm1.aspx and click Rename
  8. Type customerorder.aspx and press Enter twice
  9. Right-click the file and click View HTML Source
  10. Change the whole <form> section as follows:
     
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="customerorder.aspx.vb" Inherits="cdpub2.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    	<title>CD Publisher</title>
    	<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    	<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
    	<meta name="vs_defaultClientScript" content="JavaScript">
    	<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    	<h1>CD Publisher</h1>
    	<h2>Customer Order</h2>
    	<form method="post" action="ordersummary.aspx">
    		<table border="0" width="357">
    			<tr>
    				<td width="194">First Name:</td>
    				<td width="8"><input type="text" name="txtFirstName" size="14"></td>
    				<td width="135"></td>
    			</tr>
    			<tr>
    				<td width="194">Last Name:</td>
    				<td width="8"><input type="text" name="txtLastName" size="14"></td>
    				<td width="135"><input type="submit" value="Submit" name="btnSubmit"></td>
    			</tr>
    		</table>
    	</form>
    </body>
    </HTML>
  11. To execute the application, on the main menu, click Debug -> Start Without Debugging
  12. Type a first name and a last name for a customer
      
  13. Click Submit
     
  14. After viewing the page, close it and return to your programming environment
 

Natural Numbers

 

Bytes

A number is referred to as natural when it is considered as a whole. Examples are 2, 408, or 732945793. ASP.NET supports various types of natural numbers.

A byte is a small positive number that is less than or equal to 255. To declare a variable for such a number, use the Byte data type. Here is an example:

<% Dim pages As Byte = 16
       Response.Write(pages) %>

To convert a value or an expression to Byte, you can use the CByte() function. To do this, pass the value or the expression in the parentheses of CByte(). If the conversion is successful, CByte() would produce a Byte value.

 

Integers

An integer is a significantly large number whose value is between -2,147,483,648 and 2,147,484,647. To declare a variable that can hold such a number, use the Integer data type. Here is an example:

<% Dim numberofStudents As Integer = 2874
   Response.Write(numberofStudents) %>

To convert a value or an expression to a natural number, you can use the CInt() function by entering the value or the expression in the parentheses of this function.

 

Short Integers

A short integer is a natural number whose value is between -32768 and 32767. To declare a variable for such a number, use the Short data type. Here is an example:

<% Dim pages As Short = 874
      Response.Write(pages) %>

To convert a value or an expression to a short integer, use the CShort() function: enter the value or the expression in the parentheses of this function. If the conversion is successful, this function produces a number that is between -32768 and 32767.

 

Long Integers

If you need a variable that can hold a natural number beyond the integer, declare it using the Long data type. To convert a value or an expression to a long integer, use the CLng() function and pass the value or the expression in the parentheses of this function.

 

Practical Learning: Using Natural Numbers

  1. To use natural numbers, access the HTML Source code of the web page and change its code as follows:
     
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="customerorder.aspx.vb" Inherits="cdpub2.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <title>CD Publisher</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <h1>CD Publisher</h1>
    <h2>Customer Order</h2>
    <form method="get" action="customerorder.aspx">
    <table border="0" width="369">
        <tr>
          <td width="167">Customer Name:</td>
          <td width="187" colspan="2">
            <input type="text" name="txtCustomerName" size="26"
              value=<% =Request.QueryString("txtCustomerName") %> ></td>
        </tr>
        <tr>
          <td width="167">Number of CDs Ordered:</td>
          <td width="98"><input type="text" name="txtQuantity" size="12"
            value=<% =Request.QueryString("txtQuantity") %> >
          </td>
          <td width="89"></td>
        </tr>
        <tr>
          <td width="167">Each CD will cost</td>
          <td width="98"><input type="text" name="txtUnitPrice" size="12"
            value=<% =Request.QueryString("txtUnitPrice") %> ></td>
          <td width="89"><input type="submit" value="Calculate" name="btnCalculate"></td>
        </tr>
        <tr>
          <td width="167">And the total price is:</td>
          <td width="98">
    
            <input type="text" name="txtTotalPrice" size="12" value=
    <% =CInt(Request.QueryString("txtQuantity")) * Request.QueryString("txtUnitPrice") %> >
            
          </td>
          <td width="89"><input type="reset" value="Start Over" name="btnReset"></td>
        </tr>
      </table>
    
    </form>
    </body>
    </HTML>
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. Type a customer name, a number of CDs, and a unit price
      
  4. Click Submit
     
  5. After viewing the page, close it and return to your programming environment
 

Floating-Point Numbers

 

Single-Precision

A number is referred to as decimal or real when it contains a fractional part. Such a number is considered in two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:

Regional Options

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.

To declare a variable that would hold decimal numbers, you can use the Single data type. A variable declared a Single can store real numbers that range from ±1.5 × 10−45 to ±3.4 × 1038 with a precision of 7 digits in 32 bits. Here is an example:

Dim number As Single

To initialize a Single variable, you can assign it a natural number or a number that includes the decimal separator. Here is an example:

<%
    Dim number As Single = 128.68
    Response.Write(number)
%>

To convert a value to Single, you can use the CSng() function.

 

Double-Precision

When a variable is larger than the Single can handle and requires more precision, you should declare it using the Double data type. A variable declared as double can store very large numbers ranging from ±5.0 × 10−324 to ±1.7 × 10308 with a precision of 15 or 16 digits. Here is an example:

Dim distance As Double

To initialize a variable declared as Double, you can assign it a natural number or a number that includes the decimal separator. Here is an example:

<%
    Dim distance As Double = 287.04
    Response.Write(distance)
%>

As you can see, the Single and the Double tend to use the same types of numbers (except that the Double uses more memory and provides more precision). Because of this, a Single number may be stored in memory as if it were a Double. To explicitly specify that the number should be used as Single, you can add the F character to the right of its number. Here is an example:

<%
    Dim number As Single = 128.68F
    Response.Write(number)
%>

To convert a value to Double, you can use the CDbl() function.

 

Decimal

The Decimal data type can be used to declare a variable that would hold significantly large values. The values stored in a decimal variable can range from ±1.0 × 10−28 to ±7.9 × 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the decimal data type is suitable for currency values. Here is an example:

Dim YearlyIncome As Decimal

To initialize a Decimal variable, assign it a natural number or a number that includes the decimal separator. Here is an example:

<%
    Dim YearlyIncome As Decimal = 82455.42
    Response.Write(YearlyIncome)
%>

Once again, notice that the Decimal and the Double use the same types of numbers. When necessary, to make sure sure that a Decimal number is treated appropriately, you can add the D character to the right of its number. Here is an example:

<%
    Dim YearlyIncome As Decimal = 82455.42D
    Response.Write(YearlyIncome)
%>

To convert a value to Decimal, you can use the CDec() function.

 

Practical Learning: Using Real Numbers

  1. To convert the unit price to Double, change the cdpublisher1.aspx file as follows:
     
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="customerorder.aspx.vb" Inherits="cdpub2.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <title>CD Publisher</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <h1>CD Publisher</h1>
    <h2>Customer Order</h2>
    <form method="get" action="customerorder.aspx">
    <table border="0" width="369">
        <tr>
          <td width="167">Customer Name:</td>
          <td width="187" colspan="2">
            <input type="text" name="txtCustomerName" size="26"
              value=<% =Request.QueryString("txtCustomerName") %> ></td>
        </tr>
        <tr>
          <td width="167">Number of CDs Ordered:</td>
          <td width="98"><input type="text" name="txtQuantity" size="12"
            value=<% =Request.QueryString("txtQuantity") %> >
          </td>
          <td width="89"></td>
        </tr>
        <tr>
          <td width="167">Each CD will cost</td>
          <td width="98"><input type="text" name="txtUnitPrice" size="12"
            value=<% =Request.QueryString("txtUnitPrice") %> ></td>
          <td width="89"><input type="submit" value="Calculate" name="btnCalculate"></td>
        </tr>
        <tr>
          <td width="167">And the total price is:</td>
          <td width="98">
    
            <input type="text" name="txtTotalPrice" size="12" value=
    <% =CInt(Request.QueryString("txtQuantity")) * CDbl(Request.QueryString("txtUnitPrice")) %> >
            
          </td>
          <td width="89"><input type="reset" value="Start Over" name="btnReset"></td>
        </tr>
      </table>
    
    </form>
    </body>
    </HTML>
  2. Execute the application and preview the page in the browser
  3. Return to your programming environment and open the math project created in the previous lesson
  4. On the form, double-click the Calculate button and change its code as follows:
     
    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim Side As Double
            Dim Perimeter As Double
            Dim Area As Double
    
            Side = CDbl(Me.txtSide.Text)
            Perimeter = Side * 4
            Area = Side * Side
    
            Me.txtPerimeter.Text = CStr(Perimeter)
            Me.txtArea.Text = CStr(Area)
    End Sub
  5. Execute the application and test the page with a new value
 

Date and Time

ASP.NET provides support for dates and times values as their own data type. To declare a variable that would hold either a date value, a time value, or both, you can use the Date data type. This would be done as follows:

Dim StartDate As Date

Besides the Date data type, you can also use the DateTime data type to declare a variable that would hold a date, a time, or both.

To initialize a date or time variable, include the value between two # signs and assign that value to the variable. To specify a date value, use the formula #M/d/yyyy#. To specify a time value, you can use any variance of #HH:MM AM/PM# 

Here are three examples:

<%
    Dim StartDate As Date
    Dim StartTime As Date
    Dim StartDateAndTime As Date

    StartDate = #04/22/2004#
    StartTime = #10:42 AM#
    StartDateAndTime = #04/22/2004 10:42 AM#
%>

Remember that you can also use the DateTime data type:

<%@ Page Language="VB" %>
<html>
<head>
<title>ASP.NET Tutorials</title>
</head>
<body>
<h1>Lesson 4: Variables and Data Types</h1>

<p><b>Lecturer:</b> Benjamin Jacobson</b>
<br>
<b>Time Allocated:</b> 74 minutes</p>

<p>This lesson introduces the use of the computer memory to store some 
values that would be used while a visitor is interacting with a web page.</p>

<%
    Dim StartDate As DateTime
    Dim StartTime As DateTime
    Dim StartDateAndTime As DateTime

    StartDate = #04/20/2001#
    StartTime = #10:42 AM#
    StartDateAndTime = #04/22/2004 10:42 AM#

    Response.Write(StartDate)
    Response.Write("<br>")
    Response.Write(StartTime)
    Response.Write("<br>")
    Response.Write(StartDateAndTime)
%>
<h3>Enjoy</h3>
</body>
</html>

A date or time variable uses both values even if you initialize it with only one (this is not an anomaly; it was done like that on purpose and is very helpful as you will see in future lessons). Based on this, if you initialize the variable with only a date value, its time part would be initialized at midnight: 12:00:00 AM. If you initialize the variable with only a time value, its date part would be initialized at January 1st, 0001. Consequently, the above code would produce:


 

Previous Copyright © 2005-2008 FunctionX, Inc. Next