Article
ASP.NET 2.0: A Getting Started Guide
Arrays
Arrays are a special variety of variable that's tailored for storing related items of the same data type. Any one item in an array can be accessed using the array's name, followed by that item's position in the array (its offset). Let's create a sample page to see how it's done. The results of this code are shown in Figure 3.3:
Example 3.6. Arrays.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Arrays</title>
<script runat="server" language="VB">
Sub Page_Load()
' Declare an array
Dim drinkList(4) As String
' Place some items in it
drinkList(0) = "Water"
drinkList(1) = "Juice"
drinkList(2) = "Soda"
drinkList(3) = "Milk"
' Access an item in the array by its position
drinkLabel.Text = drinkList(1)
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:Label id="drinkLabel" runat="server" />
</form>
</body>
</html>
Example 3.7. Arrays.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Arrays</title>
<script runat="server" language="C#">
void Page_Load()
{
// Declare an array
string[] drinkList = new string[4];
// Place some items in it
drinkList[0] = "Water";
drinkList[1] = "Juice";
drinkList[2] = "Soda";
drinkList[3] = "Milk";
// Access an item in the array by its position
drinkLabel.Text = drinkList[1];
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="drinkLabel" runat="server" />
</form>
</body>
</html>

Figure 3.3. Reading an element from an array
There are some important points to pick up from this code. First, notice how we declare an array. In VB, it looks like a regular declaration for a string, except that the number of items we want the array to contain is provided in parentheses after the name:
Example 3.8. Arrays.aspx (excerpt)
Dim drinkList(4) As String
In C#, it's a little different. First, we declare that drinkList is an array by following the data type with two empty square brackets. We then specify that this is an array of four items, using the new keyword:
Example 3.9. Arrays.aspx (excerpt)
string[] drinkList = new string[4];
A crucial point to realize here is that, in both C# and VB, these arrays are known as zero-based arrays. In a zero-based array, the first item has position 0, the second has position 1, and so on through to the last item, which has a position that's one less than the size of the array (3, in this case). So, we specify each item in our array like this:
Example 3.10. Arrays.aspx (excerpt)
drinkList(0) = "Water"
drinkList(1) = "Juice"
drinkList(2) = "Soda"
drinkList(3) = "Milk"
Example 3.11. Arrays.aspx (excerpt)
drinkList[0] = "Water";
drinkList[1] = "Juice";
drinkList[2] = "Soda";
drinkList[3] = "Milk";
Note that C# uses square brackets for arrays, while VB uses standard parentheses. We have to remember that arrays are zero-based when we set the label text to the second item, as shown here:
Example 3.12. Arrays.aspx (excerpt)
drinkLabel.Text = drinkList(1)
Example 3.13. Arrays.aspx (excerpt)
drinkLabel.Text = drinkList[1];
To help this fact sink in, you might like to try changing this code to show the third item in the list, instead of the second. Can you work out what change you'd need to make? That's right--you need only to change the number in the brackets to reflect the new item's position in the array (don't forget to start at zero). In fact, it's this ability to select one item from a list using only its numerical location that makes arrays so useful in programming--we'll experience this first-hand as we get further into the book.
Functions
Functions are exactly the same as subroutines, but for one key difference: they return a value. In VB, we declare a function using the Function keyword in place of Sub, while in C#, we simply have to specify the return type in place of void. The following code shows a simple example:
Example 3.14. Functions.aspx (excerpt)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>ASP.NET Functions</title>
<script runat="server" language="VB">
' Here's our function
Function getName() As String
Return "Zak Ruvalcaba"
End Function
' And now we'll use it in the Page_Load handler
Sub Page_Load(s As Object, e As EventArgs)
messageLabel.Text = getName()
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>
Example 3.15. Functions.aspx (excerpt)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>ASP.NET Functions</title>
<script runat="server" language="C#">
// Here's our function
string getName()
{
return "Zak Ruvalcaba";
}
// And now we'll use it in the Page_Load handler
void Page_Load()
{
messageLabel.Text = getName();
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>
When the page above is loaded in the browser, the Load event will be raised which will cause the Page_Load event handler to be called, which in turn will call the getName function. Figure 3.4 shows the result in the browser.

Figure 3.4. Executing an ASP.NET function
Here's what's happening: the line in our Page_Load subroutine calls our function, which returns a simple string that we can assign to our label. In this simple example, we're merely returning a fixed string, but the function could just as easily retrieve the name from a database (or somewhere else). The point is that, regardless of how the function gets its data, we call it in just the same way.
When we're declaring our function, we must remember to specify the correct return type. Take a look at the following code:
' Here's our function
Function addUp(x As Integer, y As Integer) As Integer
Return x + y
End Function
' And now we use it in Page_Load
Sub Page_Load(s As Object, e As EventArgs)
messageLabel.Text = addUp(5, 2).ToString()
End Sub
// Here's our function
int addUp(int x, int y)
{
return x + y;
}
// And now we use it in Page_Load
void Page_Load()
{
messageLabel.Text = addUp(5, 2).ToString();
}
You can easily adapt the previous example to use this new code so that you can see the results in your browser--just replace the code inside the <script> tags in Functions.aspx with the code above.
The first thing to notice in comparing this new code to the original version of Functions.aspx is that our function now accepts parameters. Any function or subroutine can take any number of parameters, of any type (there's no need for parameter types to match the return type--that's just coincidental in this example).
We can readily use the parameters inside the function or subroutine just by using the names we gave them in the function declaration (here, we've chosen x and y, but we could have chosen any names).
The other difference between this and the function declaration we had before is that we now declare our function with a return type of Integer or int, rather than String, because we want it to return a whole number.
When we call the new function, we simply have to specify the required number of parameters, and remember that the function will return a value with the type we specify. In this case, we have to convert the integer value that the function returns to a string, so that we can assign it to the label.
The simplest way to convert an integer to a string is to append .ToString() to the end of the variable name. In this case, we appended ToString on the function call which will return an integer during execution. Converting numbers to strings is a very common task in ASP.NET, so it's good to get a handle on it early.
Converting Numbers to Strings
There are more ways to convert numbers to strings in .NET, as the following lines of VB code illustrate:
messageLabel.Text = addUp(5, 2).ToString()
messageLabel.Text = Convert.ToString(addUp(5, 2))
If you prefer C#, these lines of code perform the same operations as the VB code above:
messageLabel.Text = addUp(5, 2).ToString();
messageLabel.Text = Convert.ToString(addUp(5, 2));
Don't be concerned if you're a little confused by how these conversions work, though--the syntax will become clear once we discuss object oriented concepts later in this chapter.
Operators
Throwing around values with variables and functions isn't of much use unless you can use them in some meaningful way, and to do so, we need operators. An operator is a symbol that has a certain meaning when it's applied to a value. Don't worry--operators are nowhere near as scary as they sound! In fact, in the last example, where our function added two numbers, we were using an operator: the addition operator, or + symbol. Most of the other operators are just as well known, although there are one or two that will probably be new to you. Table 3.2, outlines the operators that you'll use most often in your ASP.NET development.
Operators Abound!
The list of operators in Table 3.2 is far from complete. You can find detailed (though poorly written) lists of the differences between VB and C# operators on the Code Project web site.
Table 3.2. Common ASP.NET operators

The following code uses some of these operators:
If (user = "Zak" AndAlso itemsBought <> 0) Then
messageLabel.Text = "Hello Zak! Do you want to proceed to " & _
"checkout?"
End If
if (user == "Zak" && itemsBought != 0)
{
messageLabel.Text = "Hello Zak! Do you want to proceed to " +
"checkout?";
}
Here, we use the equality, inequality (not equal to), and logical "and" operators in an If statement to print a tailored message for a given user when he has put a product in his electronic shopping cart. Of particular note is the C# equality operator, ==, which is used to compare two values to see if they're equal. Don't use a single equals sign in C# unless you're assigning a value to a variable; otherwise your code will have a very different meaning than you expect!
Breaking Long Lines of Code
Since the message string in the above example was too long to fit on one line in this book, we used the string concatenation operator to combine two shorter strings on separate lines to form the complete message. In VB, we also had to break one line of code into two using the line continuation symbol (_, an underscore at the end of the line to be continued). Since C# marks the end of each command with a semicolon (;), you can split a single command over two lines in this language without having to do anything special.
We'll use these techniques throughout this book to present long lines of code within a limited page width. Feel free to recombine the lines in your own code if you like--there's no length limit on lines of VB and C# code.
Conditional Logic
As you develop ASP.NET applications, there will be many instances in which you'll need to perform an action only if a certain condition is met, for instance, if the user has checked a certain checkbox, selected a certain item from a DropDownList control, or typed a certain string into a TextBox control. We check for such occurrences using conditionals, the simplest of which is probably the If statement. This statement is often used in conjunction with an Else statement, which specifies what should happen if the condition is not met. So, for instance, we may wish to check whether or not the name entered in a text box is Zak, redirecting the user to a welcome page if it is, or to an error page if it's not:
If (userName.Text = "Zak") Then
Response.Redirect("ZaksPage.aspx")
Else
Response.Redirect("ErrorPage.aspx")
End If
if (userName.Text == "Zak")
{
Response.Redirect("ZaksPage.aspx");
}
else
{
Response.Redirect("ErrorPage.aspx");
}
Take Care with Case Sensitivity
Instructions are case-sensitive in both C# and VB, so be sure to use if in C# code, and If in VB code. On the other hand, variable and function names are case-sensitive only in C#. As such, in C# you could have two variables called x and X, which would be considered to be different; in VB, they would be considered to be the same variable.
Often, we want to check for many possibilities, and specify our application to perform a particular action in each case. To achieve this, we use the Select Case (VB) or switch (C#) construct:
Select Case userName
Case "Zak"
Response.Redirect("ZaksPage.aspx")
Case "Mark"
Response.Redirect("MarksPage.aspx")
Case "Fred"
Response.Redirect("FredsPage.aspx")
Case Else
Response.Redirect("ErrorPage.aspx")
End Select
switch (userName)
{
case "Zak":
Response.Redirect("ZaksPage.aspx");
break;
case "Mark":
Response.Redirect("MarksPage.aspx");
break;
case "Fred":
Response.Redirect("FredsPage.aspx");
break;
default:
Response.Redirect("ErrorPage.aspx");
break;
}