
Beginning ASP.NET 2
.0.pdf
Code
3.Drag three text boxes, three labels, and a button onto the page, so it looks like Figure 9-1. Make sure the TextBox and Label controls are in order, so TextBox1 is at the top, followed by
TextBox2 and then TextBox 3.
Figure 9-1
4.Double-click the button to create the code-behind file and button click event, and add the following code into the event procedure:
Label1.Text = TextBox1.Text + TextBox2.Text
Label2.Text = DateTime.Parse(TextBox3.Text).ToString(“dd MMM yyyy”) Label3.Text = DateTime.Parse(TextBox3.Text).ToString()
5.Save both the Web Form and the code-behind file, and set the Web Form to be the start page (right-click the page in the Solution Explorer).
6.Press F5 to run the page and enter 3 into the first text box, enter 4 into the second text box, and 12/2/05 into the third text box.
7.Press the button and observe the results. On a machine configured with UK regional settings, you’ll see Figure 9-2.
Figure 9-2
With the regional settings set to USA, Figure 9-3 will appear.
299

Chapter 9
Figure 9-3
How It Works
There are two points to note about this page. The first is that the numbers you entered into the text boxes haven’t been added together as you might expect, and the second is that the date format changes depending on the regional settings.
Take a look at the numbers first:
Label1.Text = TextBox1.Text + TextBox2.Text
The code seems obvious, just adding two numbers together, but you have to remember that the Text property of the TextBox control returns a string. For strings, the addition operator (+) means the same as the concatenate operator (&), so it simply joins the strings together. To add the strings you would have to convert them to numbers first, like so:
Label1.Text = Convert.ToInt32(TextBox1.Text) + Convert.ToInt32(TextBox.Text)
Here the Convert class is used to convert the text to numbers, so when the addition is done the values are numbers.
For the dates, you have to consider the regional settings of the machine upon which the web server is running — this is where the code is executed. As it happens, when running the VWD web server, the machine processing the pages is the same as your browser, but on a real web site this isn’t the case. So let’s see what the code does. The first line converts the value from the text box into a DateTime type by using the Parse method, and then it converts it back into a string. The ToString method has an explicit format, where dd is the day number, MMM is the month name, and yyyy is the year:
Label2.Text = DateTime.Parse(TextBox3.Text).ToString(“dd MMM yyyy”)
The reason for converting to a date and back to a string is to show that parsing the date is systemdependent. So if you are writing a web site for a company that uses a different date format from yours, the results you see may not always be what you expect.
The final line of code shows what the default ToString method does:
Label3.Text = DateTime.Parse(TextBox3.Text).ToString()
300

Code
This simply shows the date and time. Notice that this displays the same value for the date irrespective of the regional settings. The time is shown differently but again that’s because of the regional settings on the machine. You might like to experiment with your regional settings to see how the output differs. If you do this you will need to stop the VWD web server before rerunning the application; you can do this by selecting the icon in the task tray and clicking Stop from the right mouse-button menu.
One thing you might like to experiment with is what happens if you either leave a text box empty or enter the wrong data type (for example, entering a string into the third text box for conversion to a string). Depending on what you enter you might see a different range of exceptions, a topic that is covered in more detail in Chapter 15.
Working with Arrays and Collections
Arrays and collections are two sides of the same coin; they both provide ways of storing multiple copies of data types. For example, consider having to store several names, perhaps the authors of this book. You could store them in individual strings, but then what if you wanted to print them all out? You’d need a statement for each variable. With an array or a collection you need only one variable for multiple items. You can think of arrays as cells in a spreadsheet. A single dimensional array is a single row with multiple cells, and a multi-dimensional array is multiple rows, each with multiple cells. Instead of cells, the term elements is generally used, and the index is the number of the element (the row or column number, to continue the spreadsheet analogy).
Single Dimensional Arrays
Arrays are declared in much the same way as variables, but with the addition of parentheses after the variable name. For example:
Dim Names() As String
This declares a string array called Names, but it’s an empty array because there is no number within the parentheses. The number defines the length of the array — the number of items it can hold. So to store five names you would change the declaration to the following:
Dim Names(4) As String
The use of 4 isn’t a typo here, it’s because arrays start at 0. So this array has 0, 1, 2, 3, and 4, which gives five entries. The bounds of the array are 0 to 4.
Accessing array values, either to read or assign values, follows the same rules, with the addition of the parentheses. Within the parentheses you put the index number of the element required. For example:
Names(0) = “Dave”
Names(3) = “Dan”
NameTextBox.Text = Names(4)
In this example Dave is the first entry and Dan is the fourth entry. The entries between are empty because no values have been set for them.
Trying to access an element that doesn’t exist (anything above 4 in this example) will generate an exception with the message “Index was outside the bounds of the array.”
301

Chapter 9
Arrays can also be dynamically sized when declared:
Dim Names() As String = {“Dave”, “Chris”, “Chris”, “John”, “Dan”}
Here the array has five elements with the first being assigned to Dave, the second to Chris, and so on. The braces enclose the list of items for the array.
If you need to resize an array you can use the ReDim statement:
ReDim Names(9)
This will resize the array to 10 elements, but will remove the existing values. The Preserve keyword needs to be added if you need to keep the values:
ReDim Preserve Names(9)
If the array is resized to smaller than its original size, elements will be lost.
Multi-Dimensional Arrays
Arrays aren’t limited to one dimension, so you can replicate that spreadsheet type of storage. For example, to use an array to store first and last names, you could do this:
Dim Names(4, 1) As String
Names(0,0) = “Dave”
Names(0,1) = “Sussman”
Names(1,0) = “Chris”
Names(1,1) = “Hart”
...
Names(4,0) = “Dan” Names(4,1) = “Maharry”
Here the declaration separates the dimensions by a comma. The number of elements in each dimension is included in the variable declaration, so the first dimension has five elements (0–4), and the second has two (0–1). This gives you storage like so:
|
0 |
1 |
0 |
Dave |
Sussman |
1 |
Chris |
Hart |
|
... |
|
4 |
Dan |
Maharry |
A 4-by-4 array (four rows, four columns) would be declared as follows:
Dim MyArray(3, 3) As String
302

Code
Remember, 0 counts as one element, to 0 to 3 is four elements. Adding another dimension is as simple as adding a comma and another number. So a three-dimensional array, with four elements in each dimension, would be
Dim MyArray (3, 3, 3) As String
Like single dimensional arrays, multi-dimensional ones can also be initialized at declaration time:
Dim Names(,) = {{“Dave”, “Sussman”}, {“Chris”, “Hart”}}
Like the single dimension, braces are used to surround the entries, but there are two sets of braces, one for each dimension; the outer set for the first dimension and the inner set for the second. The first names, Dave and Chris, are placed in the first dimension, and the last names, Sussman and Hart, are placed in the second dimension. So this is the same as
Dim Names(1, 1) As String
Names(0,0) = “Dave”
Names(0,1) = “Sussman”
Names(1,0) = “Chris”
Names(1,1) = “Hart”
Which style you use is a matter of personal preference. There’s no real difference between them.
Collections
Another way of storing multiple items is to use collections. These differ from arrays in that they are always dynamically allocated, which makes them more suitable for situations where the amount of data changes frequently. There are different collections for different purposes, stored in the System.Collections namespace (more on namespaces later), including
ArrayList, which provides a general collection for objects.
Hashtable, which provides storage for key/value pairs. A key/value pair is simply the storage of values, which can then later be identified by a key. In array terms the key is the index of the array element, but a Hashtable allows the key to be non-numeric.
Queue provides a first-in, first-out collection, which means that items are taken off the queue in the same order in which they were placed onto it, just like a real queue — the person who arrives first gets served first.
SortedList, which provides ordered storage for key/value pairs.
Stack provides a last-in, first-out collection, where items are taken off the stack in the reverse order in which they were placed onto it. Think of a stack of plates — the last one put onto the stack is the first off.
StringCollection, which provides a collection of strings.
There are other collections, but these are the ones you’ll probably use most frequently. Data is added to collections by calling an Add method, the parameters of which depend on the collection being used. For the StringCollection you simply supply the string to be added. For example:
303

Chapter 9
Dim Names As New StringCollection()
Names.Add(“Dave”)
Names.Add(“Chris”)
To access the entries you use the same method as an array:
NameTextBox.Text = Names(0)
This would return Dave, because the names are added in numerical order.
A HashTable is different because the index isn’t numerical, but rather string-based. With a StringCollection the index is a number, and it is assigned automatically, in order of the items added. With a HashTable you have to specify the key as well as the item you want to add. For example:
Dim Names As New Hashtable()
Names.Add(“Dave”, “Sussman”)
Names.Add(“Chris”, “Hart”)
In this example the first parameter is the key and the second is the value; this leads to them being called key/value pairs. You can also add entries without using the Add method:
Names(“John”) = “Kauffman”
There’s no real difference between using and not using the Add method, although it’s best to use Add if only because it’s clearer as to what is being done. Without the Add method the code looks more like an assignment, so you aren’t completely sure whether a new item is being added, or if an existing one is being modified.
To access the entries you use the key:
NameTextBox.Text = Names(“Chris”)
One important point about using HashTables is that the keys must be unique. So in the previous example a HashTable wouldn’t really be suitable for storing the author names, because two of the authors have the same first name. So this code would fail:
Dim Names As New Hashtable()
Names.Add(“Chris”, “Ullman”)
Names.Add(“Chris”, “Hart”)
An exception would be raised on the second Add line, because the key has already been used.
Collections, and arrays for that matter, aren’t only useful for storing native types such as strings or integers. They can also be used to store custom classes, and you’ll look at that later in the chapter. The following Try It Out, however, puts your knowledge of arrays and collections to use.
Try It Out |
Working with Arrays and Collections |
1.
2.
Create a new Web Form, called ArraysCollections.aspx.
Add a TextBox, a Button, a ListBox, and another TextBox to the form.
304

Code
3.For the text boxes set the TextMode property to MultiLine, the Columns property to 50, and the Rows property to 5. When finished it should look like Figure 9-4.
Figure 9-4
4.Enter the following code into the Click event for the button:
Dim splitChars As String = “ “
Dim words() As String
Dim wordIndex As Integer
words = TextBox1.Text.Split(splitChars.ToCharArray())
ListBox1.Items.Clear()
For wordIndex = words.Length – 1 To 0 Step -1
ListBox1.Items.Add(words(wordIndex))
Next
Dim paragraph As String = String.Empty
For Each word As ListItem In ListBox1.Items paragraph &= word.Value & “ “
Next
TextBox2.Text = paragraph
5.Save the files, and set ArraysCollections.aspx as the start page.
6.Press F5 to run the page and enter Wrox United are the best into the first text box.
7.Press the button and you will see the screen shown in Figure 9-5.
You can see that the sentence in the first text box has been split into its component words, that those words have been entered into the list box in reverse order, and then the words have been combined into the second text box.
305

Chapter 9
Figure 9-5
How It Works
The first three lines of the code simply define variables. The first, splitChars, is a string containing the characters that will be used to split the sentence. The second, words, is an array of strings, and the third, wordIndex, is an Integer that will be used to count through the array:
Dim splitChars As String = “ “
Dim words() As String
Dim wordIndex As Integer
Next, the sentence entered into the text box is split into an array, using the Split method. Although it looks like Split is a method of the Text property, you must remember that the Text property returns a String — so Split is a method of the String class. The parameter passed into the string is not the splitChars variable itself, but splitChars converted to a character array (using the ToCharArray method). This is because a character array is the required type for the Split method, which allows a great deal of flexibility in splitting strings:
words = TextBox1.Text.Split(splitChars.ToCharArray())
At this stage the words array now contains a separate entry for each word in the sentence, ready for addition into the list box. Before the words are added to the list the existing Items collection is cleared, which stops the list from getting ever bigger if the button is clicked multiple times. Then you loop through the words array, but loop backwards, adding each word into the list:
ListBox1.Items.Clear()
For wordIndex = words.Length – 1 To 0 Step -1
ListBox1.Items.Add(words(wordIndex))
Next
Don’t worry too much about the exact syntax of the looping — you’ll get to that later in the chapter.
306

Code
Once the words are in the list they can be removed again, into another string. This has an initial value that might seem unusual — String.Empty — but this is quite a common thing for initializing strings:
Dim paragraph As String = String.Empty
String.Empty is a special value that indicates that the string is, well, empty. This is different from a string assigned to “”, which has a value, albeit a string of length zero that doesn’t contain any characters. The reason for having a distinction between a zero length string and an empty string is that it allows you to detect whether the string has been set or changed from its initial value. One of the reasons for declaring an initial value is that without it you get a warning in VWD, but on a later line, indicating that the paragraph variable is being used before it has been set. In this case it doesn’t matter, but reducing warnings in VWD means it’s easier to spot warnings and errors that do matter.
You now loop through the Items collection of the list box, and the Items collection contains ListItem objects. The Value of each ListItem is simply appended to the paragraph string, along with a space:
For Each word As ListItem In ListBox1.Items paragraph &= word.Value & “ “
Next
Finally, the paragraph is displayed in the second text box:
TextBox2.Text = paragraph
This may seem an overly lengthy way to reverse the words in a sentence, but the point of the exercise is to show that there are different ways of working with arrays and collections.
Deciding Whether to Use Arrays or Collections
There are pros and cons of using both arrays and collections, and the decision of which to use can sometimes be confusing. In general if the number of elements isn’t going to change, an array is best; it’s efficient, fast, and provides easy access to the elements. If you need to change the number of elements, or insert elements in between others, then a collection is best.
Both arrays and collections can, like some of the data objects, be used for data binding. For example, the Wrox United shop could have a list of delivery methods in a drop-down list:
Dim delivery() As String = {“Post”, “Courier”, “International”}
DeliveryDropDownList.DataSource = delivery
DeliveryDropDownList.DataBind()
Here the array is simply used as the source to which to bind the list. Collections can also be used in this manner. Data binding was covered in Chapter 7.
Enumerations
Enumerations are a custom data type where the value can be one of a number of values. This is easier to see with an example, so let’s look at the Calendar control. This is a complex control and has many properties to allow its look to be changed, one of which is the DayNameFormat (see Figure 9-6).
307

Chapter 9
Figure 9-6
The format must be one of these five values (Full, Short, FirstLetter, FirstTwoLetters, and Shortest), and no other, so there needs to be a way of ensuring only these values can be selected. This is where enumerations come in because enumerations restrict the variable to a set of known values. The syntax for creating an enumeration is as follows:
Public Enum EnumerationName
enumeration values
End Enum
What this does is declare a new type, with the name of the type being whatever name you give it as EnumerationName. This type is a special type where the values can only be one of the supplied list. For example, the DayNameFormat is an enumeration, which has been created like so:
Public Enum DayNameFormat Full
[Short] FirstLetter FirstTwoletters Shortest
End Enum
Because this is a new type it can be used in variable declarations:
Dim dayFormat As DayNameFormat
dayFormat = DayNameFormat.FirstLetter
This declares a new variable of the enumeration type — DayNameFormat. Then it assigns a value to the variable, and the value assigned is one of the defined values. This shows as the enumeration name and value separated by a period. What’s great is that you get IntelliSense, so you can pick from a list of the known values when assigning the variable.
Enumerations provide a way to have a human-readable value associated with a number. In the preceding example no numbers are explicitly assigned, so they are created automatically, starting at 0. So here
308