Wednesday, March 21, 2012

How to Use a HashTable in a Visual Basic Application


1. Open a new Visual Basic project. Double-click the 'Button' control four times to add 'Button1' through 'Button4' to the form and arrange them as you like. Change the 'Text' property for 'Button1' to 'Add,' for 'Button2' to 'Remove,' for 'Button3' to 'Show All' and for 'Button4' to 'Clear.'
2. Press 'F7' to open the code window. Type the following code on the first line:Imports System.CollectionsThis imports the System.Collections namespace into the project. It contains the Hashtable class.
3. Open the 'Form1' class and type the following code:Dim MyHashTable As New Hashtable()This creates a new object called 'MyHashTable' that uses the Hashtable class.
4. Open the 'Button1_Click' subroutine and type the following code:TryMyHashTable.Add('First', 'Gold')MyHashTable.Add('Second', 'Silver')MyHashTable.Add('Third', 'Bronze')Catch ex As ExceptionMessageBox.Show('Duplicate Key')End TryThese lines use the 'Add' method to add three new items to the hash table with 'First,' 'Second' and 'Third' as the keys and 'Gold,' 'Silver' and 'Bronze' as their respective values. You can get the key-value pairs from anywhere else in the program, such as a user InputBox, TextBox controls or other selections at run time. Adding these items in a 'try-catch' block ensures that if you try to add an item with a key that already exists in the hash table, it does not crash the program.
5. Open the 'Button2_Click' subroutine and type the following code:If (MyHashTable.Count = 0) ThenMsgBox('HashTable is empty')ElseMyHashTable.Remove(MyHashTable.Count)End IfThese lines use the 'Count' method to see if the hash table is empty already. If so, the program tells the user; if not, it removes the most recent item. You can program alternative ways to remove items from the hash table.
6. Open the 'Button3_Click' subroutine and type the following code:If MyHashTable.Count = 0 ThenMsgBox('No items in HashTable')ElseFor i = 0 To MyHashTable.Count - 1MsgBox(MyHashTable.Keys(i).ToString & ', ' & MyHashTable.Values(i))Next iEnd IfThese lines check first to see if any entries exist in the hash table. If not, the user is informed that the table is empty; otherwise, all of the key-value pairs are displayed. Because hash tables use zero-indexing, you need to count up to this hash table's 'count' minus one.
7. Open the 'Button4_Click' subroutine and type the following code:MyHashTable.Clear()This method clears all entries in the hash table. You do not need to check first if the table is empty or not because clearing an empty table does not cause an error.