Storing Collections of Data in Code


Storing single values in our code is all very well, but sometimes we might want to store more than one related value in our code and collect these values together. For example, we could store a list of the colors of the rainbow; red, orange, yellow, green, blue, indigo, and violet, and refer to these values in our code.

You may recall from Chapter 3 that we looked at creating a collection of values using the ListItem Collection Editor builder in Web Matrix. (This is in the Try It Out section entitled Getting the User Details.)

There are several different types of collections in .NET that we can use for storing values. These are arrays, array lists, and hashtables, so let's take a look at each of them in turn.

Arrays

A simple list array is used to store a series of items, and each item is referenced by a number. Let's take a look at a simple array of string values. The following array is called ColorList and, as you can expect, contains the colors of the rainbow:

Item

Value (String data type)

0

Red

1

Orange

2

Yellow

3

Green

4

Blue

5

Indigo

6

Violet

In this array, we are storing the seven colors of the rainbow, and giving each of them an individual index number. Indexes in Visual Basic .NET start from 0, so although there are seven items, our numbering only goes up to 6.

So, we can store information in an array, but what can we do with it? Well, somewhere, over the rainbow, there's an answer – let's take a look at an example of arrays in action. Buckle your seatbelt, Dorothy, 'cause Kansas is going bye-bye!

Try It Out—Working with Arrays

In this example, we'll take our simple colorful array and incorporate it into a simple page.

  1. Create a new ASP.NET page and call it Arrays.aspx.

  2. Start by typing in something like the following text onto the page: Select a color from the list:.

  3. Next, drag a DropDownList control onto the page, and change its ID property to ddlColorList.

  4. Drag a Button control onto the page next to the DropDownList control, and change its ID property to btnSelectColor. Also, change its Text property to Click here!.

  5. Place the cursor to the right of the button, then press Return to start a new line. Add a Label control to the page, clear its Text property, and set its ID to lblOutputMessage. You should now see the following in Design view:

    click to expand

  6. Now switch to the Code view. Firstly, we need to enter some code that creates and fills the array, fills the drop-down list with the colors:

     ' Create an empty array with seven elements Dim ColorList(6) as String Sub Page_Load  ' Add the colors to the array  ColorList(0) = "Red"  ColorList(1) = "Orange"  ColorList(2) = "Yellow"  ColorList(3) = "Green"  ColorList(4) = "Blue"  ColorList(5) = "Indigo"  ColorList(6) = "Violet"  If Not Page.IsPostback  Dim ColorName as String  ' Display the colors in our drop-down list  For Each ColorName in ColorList  ddlColorList.Items.Add(ColorName)  Next  End If End Sub 
  7. Then, go back to the Design view and double-click on the button to have the Click event handler wired up by Web Matrix for us. You will need to add the following code so that the page can react to that event:

    Sub btnSelectColor_Click(sender As Object, e As EventArgs)  ' Display the confirmation message on the page  lblOutputMessage.Text = "You selected " & ddlColorList.SelectedItem.Value  lblOutputMessage.ForeColor = _  System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text) End Sub

  8. Run the page, select a color, and click the button. You should see something like the following:

    click to expand

How It Works

This example produces some quite simple results, but as we were putting it together, we've used quite a few useful tools along the way. Let's take a look at what we've done in a bit more detail.

The first thing we do in our code is to create our blank array:

' Create an empty array with seven elements Dim ColorList(6) as String

We have to do this outside all of the methods on our page because we need to be able to access the array from all of them. The scope of our array is crucial for our application to work, as we discussed in the previous chapter. We also specify the data type of all of the elements in the array in this statement. An array can only store items of the same type.

Once we have our blank array, we need to fill it with our list of colors. We want our drop down list to have the list of colors in it when the page is loaded, so we add some code to the Page_Load event-handler, which runs each time the page is loaded.

Sub Page_Load   ' Add the colors to the array   ColorList(0) = "Red"   ColorList(1) = "Orange"   ColorList(2) = "Yellow"   ColorList(3) = "Green"   ColorList(4) = "Blue"   ColorList(5) = "Indigo"   ColorList(6) = "Violet" 

When the page is loaded, we populate our array with our colors, as we saw earlier. Now we need to fill the list with these values, but we only want to do this the first time a page is loaded, so we use a condition we first met in Chapter 3 to determine if the page is being posted back to the server or not:

  If Not Page.IsPostback

So, let's now add the colors to the listbox:

    Dim ColorName as String     ' Display the colors in our drop-down list     For Each ColorName in ColorList       ddlColorList.Items.Add(ColorName)     Next   End If End Sub

We create a temporary variable, called ColorName, to store an individual value from the array. We then use a For Each loop to work through the colors in our array, one by one, by working with each value in the array in turn. The first value in the array is Red, so the first item added to the drop-down list is Red. The next one is Orange, and so on, and so on.

The final part of our code writes our message to the screen when the button is clicked:

Sub btnSelectColor_Click(sender As Object, e As EventArgs)   ' Display the confirmation message on the page   lblOutputMessage.Text = "You selected " & ddlColorList.SelectedItem.Value   lblOutputMessage.ForeColor = _     System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text) End Sub

We start by displaying the message itself, taking the currently selected color from the drop-down box, and adding that to the end of a fixed message. The message is displayed as the Text property of the Label control. The last part of our code changes the color of the message:

  lblOutputMessage.ForeColor = _     System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text) End Sub

In this final step, we are setting the ForeColor property of our label to the currently selected color from the drop-down box. It's a little more complicated than that though. The drop down box has a list of string values. The ForeColor property requires an object of type Color in order to set the color of the text. We need to have some way to generate the right kind of object so that we can set the color. This is where the FromName() method comes in.

Later in this chapter, we'll learn more about the System.Drawing part of this method call. All we need to understand for now is that .NET has a Color class, stored within the System.Drawing namespace.

Important

We introduced two important new words in that last paragraph – class and namespace. As we'll learn later in the chapter, classes and namespaces are a core part of .NET, and an essential concept to understand if you want to be a proficient ASP.NET developer.

The Color class contains a FromName() method. This method takes a string of a color, and creates an object of type Color from this name. The name we pass in is the currently selected item from our drop-down list, generating a Color object representing this color. This means we can change the color of our text.

So, we've used a simple array on a drop-down list on a page. Arrays are a great way of storing a list of values of a specific type. We could store an array of integers, an array of dates, and so on. Arrays are just a way of collecting together a set of related values of a certain type.

Taking it Further – Arrays

A cool feature of arrays is that they can be sorted. If we wanted to turn our rainbow inside out, we could do so by reversing the order of the colors in our list, or we could even sort our colors alphabetically. All we need to do is add a single line of code to our example.

If you want to try this out, try adding the following line to your example to sort your array in reverse order:

  ' Add the colors to the array   ColorList(0) = "Red"   ColorList(1) = "Orange"   ColorList(2) = "Yellow"   ColorList(3) = "Green"   ColorList(4) = "Blue"   ColorList(5) = "Indigo"   ColorList(6) = "Violet"  Array.Reverse(ColorList) 

Alternatively, add the following to sort the array alphabetically:

  ...   ColorList(6) = "Violet"  Array.Sort(ColorList) 

If you tried these two modifications out, you would end up with the following screens – after saving and restarting the page of course:

or

On the left screenshot, the order of the array has been reversed. On the right-hand image, the array has been sorted alphabetically.

What if we want to insert a value between two existing elements? Well, it is possible to extend the boundary of our arrays by using the Visual Basic .NET ReDim statement. This will allow us to create a new array that is larger but empty, or we can preserve the existing content, and add more elements to our current list. Let's take a quick look.

If we want to add another color to our list of colors, we can either amend the original code to create an array that stores 8 colors, or we can change the size of our array dynamically later on in our code, using something like the following:

Dim ColorList(6) as String Sub Page_Load   ColorList(0) = "Red"   ...   ColorList(6) = "Violet"     ReDim Preserve ColorList(7)  ColorList(7) = "Magenta" 

This will add Magenta to our list of colors for the benefit of those who feel there's not enough pink in the rainbow:

Arrays aren't actually that flexible though. It would be great if we didn't have to resize our arrays when we needed to add more elements, and instead could simply add more and more elements whenever we needed them. It would also be great if we could insert elements into the array. For operations like this, we need a different type of collection. Enter the ArrayList!

Array Lists

An ArrayList is a special kind of array that has some advantages over the simple array. With an ArrayList, we can store a collection of elements, and add or remove items from that collection, all without any real difficulty. So, it's easier to use, and it can do more than an array – so why use arrays in the first place? The answer is that simplicity comes at a cost, because the performance of an application can suffer a bit if you use an ArrayList (this is because it requires more processing power than a simple array, which can have significant performance implications on larger-scale web applications). If you're only using a fixed list of values, such as the seven colors in the rainbow, an array is perfectly adequate.

Let's look at how ArrayLists work by expanding our previous example.

Try It Out—Using ArrayLists

For this example, make a copy of your Arrays.aspx page in the state we finished with it in the previous Try It Out. The reason I say this is because you may have played with some of the code in the previous section to see the effects of reversing and sorting arrays. Rename the copy to ArrayLists.aspx.

  1. Firstly, in the Design view, position your cursor after the drop-down list control (before the button), and then press Return twice to add a couple of new lines. Type the following text to prompt the user: Then select a font style from the list:.

  2. Add another drop-down box at the end of this text and set its ID property to ddlFontList. Your design view should now look like this:

    click to expand

  3. There are several small pieces of code that we need to add to our example to add ArrayList functionality, so take care to add all of the following four sections of highlighted code:

    Dim ColorList(6) as String Dim FontList as new ArrayList() Sub Page_Load ...   ColorList(6) = "Violet"  FontList.Add("Times New Roman")  FontList.Add("Arial")  FontList.Add("Verdana")  FontList.Add("Comic Sans MS")   If Not Page.IsPostback     Dim ColorName as String     For Each ColorName in ColorList       ddlColorList.Items.Add(ColorName)     Next  ddlFontList.DataSource = FontList  ddlFontList.DataBind()   End If End Sub Sub btnSelectColor_Click(sender As Object, e As EventArgs)  lblOutputMessage.Text = "You selected " & _  ddlColorList.SelectedItem.Value & " text written in " & _  ddlFontList.SelectedItem.Value   lblOutputMessage.ForeColor = _     System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)  lblOutputMessage.Font.Name = _  ddlFontList.SelectedItem.Text End Sub

  4. After adding all that lot, it's time to see it in action! Run the example, select a color and a font, then click the button:

    click to expand

How It Works

Let's look at the new sections of code that we added. The first line simply created a new ArrayList object, ready to hold some information:

Dim FontList as new ArrayList()

We don't have to specify how many items our list will contain – we simply declare that we're creating a new ArrayList. We include the new keyword to specify that we are creating a new instance of the ArrayList object.

So, in our Page_Load event, we add values to our ArrayList:

  FontList.Add("Times New Roman")   FontList.Add("Arial")   FontList.Add("Verdana")   FontList.Add("Comic Sans MS")

The syntax we use when adding values to an ArrayList is slightly different from that of an array. We add items to an ArrayList by using its Add() method, without specifying a position in the list.

We also used a slightly different method to add these items to the second drop-down list, a process known as data binding:

    ddlFontList.DataSource = FontList     ddlFontList.DataBind() 

Data binding, as we'll see in Chapters 8 through to 10, is the process of adding all the items in a collection to a web control that can display a collection. Binding to an array is a very simple process – we set the data source for our control to the collection we want to bind to, then we call the DataBind() method to initiate the binding process. It's a little easier than iterating through the collection, as we did before, but it has the same effect. Our second drop down list box will now contain a list of fonts.

Finally, we alter our output message to integrate a font into the output:

  lblOutputMessage.Text = "You selected " & _     ddlColorList.SelectedItem.Value & " text written in " & _     ddlFontList.SelectedItem.Value

The actual text of the message is changed slightly to include the two different values. Then we set the color as before:

  lblOutputMessage.ForeColor = _     System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)

Finally, we change the font of our output text to the font specified in the font list.

  lblOutputMessage.Font.Name = _     ddlFontList.SelectedItem.Text

Taking it Further – ArrayLists

We said earlier that ArrayLists make the process of adding and removing elements very simple. Let's take a look at how we could extend our example to incorporate this.

Try It Out—Adding New Items to an Existing ArrayList
  1. Head back to the Design view and add another line to the bottom of our page. Add the text: Enter a new font for the list:.

  2. Add a TextBox to the page, and set its ID to txtAddFont. Then add a Button, set its Text property to Add New Font and set its ID to btnAddFont. You should have the following layout in Design view:

    click to expand

  3. Double-click the Add New Font button, and add the following code:

    Sub btnAddFont_Click(sender As Object, e As EventArgs)  FontList.Add(txtAddFont.Text)  ddlFontList.DataSource = FontList  ddlFontList.DataBind() End Sub
  4. Run the page once more, and add a new font to the page by entering the name of a font installed on your system, and clicking the Add New Font button. Once you've done this, try outputting the message in this new font:

    click to expand

How It Works

Well, it certainly works, but Wingdings is hardly a readable font! Still, you can choose any font on your system, so if you like to display symbols instead of text for that Matrix look, that's perfectly acceptable.

The new code we added was fairly simple – let's take a look:

Sub btnAddFont_Click(sender As Object, e As EventArgs)   FontList.Add(txtAddFont.Text)   ddlFontList.DataSource = FontList   ddlFontList.DataBind() End Sub

We add the new font by using the Text property of the textbox we've just added. We then have to re-bind our list of fonts to our drop-down list. The new font is added to the end of the existing list.

Our example has a couple of limitations, for example, if you try to add a font that doesn't exist, you will not be able to change the text to the new font style (there isn't a font called "boing" on my web server machine, but the font name boing would still be added to the list if I were to try to add a font called this. Selecting it from the font list will leave the text written in the default font (Times New Roman).

The other limitation is that adding another new font to the list will remove the previously added font. We didn't store the new font anywhere, so if you want to remember all of the fonts added, you need to add more code.

One of the advantages of ArrayLists is that we can insert values into any point in the list. If we wanted to specify the location that our new font would occupy in the list, we could have used the following syntax:

  FontList.Insert(1,txtAddFont.Text) 

This would insert our new font, in our case, Wingdings, as the second item in the list (since the items are ordered starting from zero, as with every array). We can remove items from the list quite easily too:

  FontList.Remove("Verdana") 

This syntax can be used to remove a named item. Alternatively, we can remove by the current index number of the items:

  FontList.RemoveAt(0) 

This will remove the first item in the list, in our case, Times New Roman. Whenever we add, insert, or remove items, the index numbers of the items adjust accordingly.

Let's move on now to look at another type of collection, the Hashtable.

Hashtables

Hashtables are a great way of associating values with keys that can identify them. For example, when we used the ArrayList, we could refer to the index number of each value, but we needed to figure out the number corresponding to the item we required. With a Hashtable, we have a way of replacing the index number system with a key that we specify for each item, which relates to a corresponding value.

It all sounds a bit confusing, so let's take a look at an example:

Key

Value

UK

United Kingdom

US

United States

AR

Argentina

IN

India

AU

Australia

In this simple list of keys and values, we can relate the name of a country to its two digit country code, so rather than having to type out the whole of "United Kingdom", we can use the key value "UK" if we prefer. Let's take a look at the Hashtable in action by extending our example.

Try It Out—Keys, Values, and Hashtables

So far, the text we've used has been quite uninspiring. We're going to extend the example to include something more interesting to read.

  1. Open up ArrayLists.aspx once again. We won't be adding fonts in this example, so we will base this example on the earlier ArrayLists example. Save the file as Hashtables.aspx.

  2. We can now start modifying our example. In the Design view, we will need to delete the final line on the page, from our previous example. This is the one we used previously to add a font to the drop-down list. Then, add another line on the form, with the text as above. You'll also need to add in a drop-down list (with an ID of ddlQuoteList), so that your design-time view looks as follows:

    click to expand

  3. Head back into code view, and add the following highlighted lines of code. Make sure that the text of the "Joke" is all on one line in your code – we've had to spread it over two lines because of the limitations of page width! Again, we've omitted a full listing to save space:

    Dim ColorList(6) as String Dim FontList as new ArrayList() Dim QuoteList as new Hashtable() Sub Page_Load   ...   FontList.Add("Comic Sans MS")  QuoteList.Add ("Quotation", _  "English? Who needs that? I'm never going to England. ")  QuoteList.Add ("Joke", _  "There's a pizza place near where I live that sells only slices... in the back you can see a guy tossing a triangle in the air...")  QuoteList.Add ("Wisdom", _  "There is a difference between knowing the path and walking the path.")  QuoteList.Add ("Saying", _  "A rolling stone gathers no moss.")   If Not Page.IsPostback     ...     ddlFontList.DataSource = FontList     ddlFontList.DataBind()  ddlQuoteList.DataSource = QuoteList.Keys  ddlQuoteList.DataBind()   End If End Sub Sub btnSelectColor_Click(sender As Object, e As EventArgs)  lblOutputMessage.Text = QuoteList(ddlQuoteList.SelectedItem.Text)   lblOutputMessage.ForeColor =      System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)   lblOutputMessage.Font.Name = ddlFontList.SelectedItem.Text End Sub 

    Note

    Remember to delete the Click event handler for the btnAddFont button, and its contents, as that button no longer exists.

  4. Run the page, enter some values, and select the message you'd like to see. Then click the button. You should see the following:

    click to expand

How It Works

We now have the option to display four different types of messages. Personally, I'm rather fond of Steven Wright jokes, but you can feel free to display quotes from the Simpsons, wise quotes from The Matrix, strange proverbs, or whatever you feel like.

Let's see how the code worked. Firstly, we declared a new Hashtable object:

Dim QuoteList as new Hashtable()

Then we have to fill our newly-created Hashtable with data:

  QuoteList.Add ("Quotation", _    "English? Who needs that? I'm never going to England. ")   QuoteList.Add ("Joke", _    "There's a pizza place near where I live that sells only slices... in the back you can see a guy tossing a triangle in the air...")   QuoteList.Add ("Wisdom", _    "There is a difference between knowing the path and walking the path.")   QuoteList.Add ("Saying", _     "A rolling stone gathers no moss.") 

Notice that the Add() method takes two arguments, the key, and the value. It's important to remember, as mentioned above, that because of page limitations, the joke value appears to break over two lines but you need to make sure that the value is all on one line in your code.

Next, we use code to bind our Hashtable values to the type of quote drop-down list, which looks similar to that used to bind the list of fonts to the font list drop-down box:

    ddlQuoteList.DataSource = QuoteList.Keys     ddlQuoteList.DataBind()

The main difference from our previous binding statement is that we are specifying that we want to bind the Keys in the Hashtable to the list of values in the drop-down list, so we will display only the shortened values in the box. The keys are still associated with their values, though.

Finally, we change the output message to display the selected quote:

  lblOutputMessage.Text = QuoteList(ddlQuoteList.SelectedItem.Text)

We can then apply the correct font and color to the quote as appropriate.

  lblOutputMessage.ForeColor = _     System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)   lblOutputMessage.Font.Name = ddlFontList.SelectedItem.Text

Taking it Further – The SortedList Collection

A slightly different type of collection is the SortedList collection. This collection is very similar to the Hashtable we've just used, except that the keys are sorted alphabetically automatically, regardless of the order in which they're entered, for example:

Hashtable sorting

SortedList sorting

Quotation

Joke

Joke

Quotation

Wisdom

Saying

Saying

Wisdom

All we'd have to do to change to a SortedList collection is to change the line that creates
the Hashtable:

 Dim QuoteList as new SortedList() 

This would produce the following:

click to expand

Notice that the list of types of quotes are now sorted alphabetically, even though we didn't change the order in which they were added to the collection in our code.

In our examples, we've worked exclusively with the drop-down list control to display our collections, but there are many other controls we can use for this purpose, including the ListBox, and the DataGrid controls. We'll be looking at these controls in more detail when we look at working with data stored in a database starting in Chapter 8.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net