You are currently offline, waiting for your internet to reconnect

How to work with the HashTable collection in Visual Basic .NET or in Visual Basic 2005

This article was previously published under Q307933
SUMMARY
This article provides information about the HashTable collection. Because hashing eliminates the need for costly searching of data to retrieve the data, you can use hashing to efficiently retrieve data. Hashing uses the value of the key itself to locate of the data.

The Base Class Libraries offer a HashTable class that is defined in the System.Collections namespace so that you are not required to code your own hash tables.

back to the top

Steps to Build the Sample

A HashTable collection stores a (Key, Value) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable. This sample uses several instances of a simple Person class to store in a HashTable. The last name is used as the Key.
  1. Open Microsoft Visual Studio .NET or Microsoft Visual Studio 2005, and create a Windows Application project in Visual Basic .NET or in Visual Basic 2005. Form1 is added to the project by default.
  2. In Solution Explorer, right-click the project name, point to Add, and then click Add Class to add a Class module. Class1 is added to the project by default.
  3. In the Add New Item dialog box, click Open.

    Note In Visual Studio 2005, click Add instead of Open.
  4. Replace any code in the Class1 module with the following code:
    Public Class Person    Public Fname, Lname As String    Sub New(ByVal FirstName As String, ByVal LastName As String)        Fname = FirstName        Lname = LastName    End Sub    Public Overrides Function ToString() As String        Return Fname + " " + Lname    End FunctionEnd Class						
    The Person class has one constructor that takes the FirstName and LastName parameters and assigns these parameters to the local variables. The ToString function overrides ToString from the Object class to return Fname and Lname concatenated together.
  5. In Form1.vb, add the following Imports statement to the top of the code module:
    Imports System.Collections					
  6. Create a form-level Hashtable object, and declare three variables of type Person. Add the following code to the Form1 class:
    Dim MyTable As New Hashtable()'For simplicity, create three Person objects to add to the HashTable collection.Dim Person1, Person2, Person3 As Person  					
  7. In the following steps, use the Add method of the Hashtable object to add three Person objects to the Hashtable in a try-catch block. The try-catch block catches the exception and displays a message if duplicate keys exist.
    1. Place a Button control on Form1, and change the Text property to Add Elements.
    2. Double-click the button to open its Code window, and paste the following code in the Button1_Click event:
      Person1 = New Person("Karen", "Berge")Person2 = New Person("David", "Campbell")Person3 = New Person("Jim", "Kim")'The Add method takes Key as the first parameter and Value as the second parameter.Try     MyTable.Add(Person1.Lname, Person1)     MyTable.Add(Person2.Lname, Person2)     MyTable.Add(Person3.Lname, Person3)Catch ae As ArgumentException     MessageBox.Show("Duplicate Key")End Try						
  8. The Hashtable object provides an indexer. In the following steps, index with the Key to access the value that is stored at the hashed location.
    1. Add a Button control to Form1, and change the Text property to Get Items.
    2. Double-click the button, and paste the following code in the Button2_Click event:
      'Use the indexer of the Hashtable class to retrieve your objects. The indexer takes 'Key as a parameter and accesses it with the Hashed location.        Try     MessageBox.Show(MyTable(Person1.Lname).ToString)     MessageBox.Show(MyTable(Person2.Lname).ToString)     MessageBox.Show(MyTable(Person3.Lname).ToString)Catch ex As NullReferenceException     MessageBox.Show("Key not in Hashtable")End Try						
  9. In the following steps, use the Remove method to remove a single item from the HashTable collection:
    1. Add a Button control to Form1, and change the Text property to Remove Item.
    2. Double-click the button, and paste the following code in the Button3_Click event:
      'Use the Count property.If (MyTable.Count = 0) Then     MessageBox.Show("There are no items in HashTable")Else     MessageBox.Show("The count before removing an Item is" & " " & MyTable.Count)     MessageBox.Show("Removing value stored at key value (Berge)")     'Remove the object that is stored at the Key value Person1.Lname.     MyTable.Remove(Person1.Lname)End If						
  10. In the following steps, enumerate the items that are stored in the HashTable collection.
    1. Add a Button control to Form1, and change the Text property to Enumerate.
    2. Double-click the button, and paste the following code in the Button4_Click event:
      Dim Enumerator As IDictionaryEnumeratorEnumerator = MyTable.GetEnumerator()If (MyTable.Count = 0) Then     MessageBox.Show("The HashTable is empty")Else     MessageBox.Show("Enumerating through the HashTable collection")     While Enumerator.MoveNext()          MessageBox.Show(Enumerator.Value.ToString())     End WhileEnd IfDim MyKeys As ICollectionDim Key As ObjectIf (MyTable.Count = 0) Then     MessageBox.Show("The HashTable is empty")Else     MessageBox.Show("Accessing keys property to return keys collection")     MyKeys = MyTable.Keys()     For Each Key In MyKeys          MessageBox.Show(Key.ToString)     NextEnd If 							
      This code declares a variable of type IDictionaryEnumerator and calls the GetEnumerator method of the HashTable collection. With the Enumerator returned, the code enumerates through the items in the collection and uses the Keys method of the HashTable to enumerate through the keys.
  11. In the following steps, use the Clear method to clear the HashTable.
    1. Add a Button control to Form1, and change the Text property to Clear.
    2. Double-click the button, and paste the following code in the Button5_Click event:
      MyTable.Clear()MessageBox.Show("HashTable is now empty")						
  12. Follow these steps to build and run the application:
    1. Click Add Items. Note that three Person objects are added to the HashTable collection.
    2. Click Get Items. Note that the indexer obtains the items in the HashTable collection. The three newly added items are displayed.
    3. Click Remove Item. Note that the item at the "Berge" key location is deleted.
    4. Click Enumerate. Note that IDictionaryEnumerator enumerates through the items in the HashTable collection.
    5. Click Clear. Note that all the items are cleared from the HashTable collection.
NOTE: The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, places, or events is intended or should be inferred.

back to the top
try...catch
Properties

Article ID: 307933 - Last Review: 12/06/2006 23:18:59 - Revision: 3.3

Microsoft Visual Basic 2005, Microsoft Visual Basic .NET 2003 Standard Edition, Microsoft Visual Basic .NET 2002 Standard Edition

  • kbvs2005swept kbvs2005applies kbhowtomaster KB307933
Feedback
type="text/JavaScript" async=""> var varAutoFirePV = 1; var varClickTracking = 1; var varCustomerTracking = 1; var Route = "76500"; var Ctrl = ""; document.write("