Microsoft KB Archive/815673

= How to use the Hashtable collection in Visual C++ =

Article ID: 815673

Article Last Modified on 1/13/2006

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft .NET Framework 1.1
 * Microsoft Visual C++ 2005 Express Edition

-







For a Microsoft Visual C# .NET version of this article, see 309357.



For a Microsoft Visual Basic .NET version of this article, see 307933.

IN THIS TASK

 * SUMMARY
 * Requirements
 * Steps to build the sample



SUMMARY
This step-by-step article describes how to use the Hashtable collection. By using hashing to retrieve the data, you do not have to use the costly searching mechanism. Hashing uses the value of the key itself to locate the data.

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

back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
 * Microsoft .NET Framework fundamentals
 * Object-oriented programming concepts

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio 2005
 * The Microsoft .NET Framework 1.1

back to the top

Steps to build the sample
A Hashtable collection stores a key-and-value pair (key, value). The Hashtable collection uses the key to hash and obtain the storage location. The key is immutable and cannot have duplicate entries in the Hashtable collection. This sample uses several instances of a simple Person class to store records in a Hashtable collection. The last name is used as the key.  Start Visual Studio .NET 2003 or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. Under Project Types, click Visual C++ Projects.

Note In Microsoft Visual Studio 2005, click Visual C++ under Project Types. Under Templates, click Windows Forms Application (.NET).

Note In Microsoft Visual Studio 2005, click Windows Forms Application under Templates. In the Name box, type 815673, and then click OK.

By default, Form1 is added to the project. On the Project menu, click Add Class.</li> In the Add Class dialog box, click Generic C++ Class under Templates, and then click Open.

Note In Microsoft Visual Studio 2005, click C++ Class under Templates.</li> In the Generic C++ Class Wizard, type Person in the Class name box, and then click Finish.</li> Open the Person.cpp file, and then delete the code for the constructor and the code for the destructor.</li>  Open the Person.h file, and then replace the existing code with the following code. using namespace System;
 * 1) pragma once

public __gc class Person { public: String *Fname, *Lname; public: Person(String *FirstName, String *LastName) {       Fname = FirstName; Lname = LastName; }   String* ToString {       return String::Concat(Fname, S&quot; &quot;,Lname); } }; The Person class has one constructor that takes the FirstName parameter and the LastName parameter. It assigns these parameters to the local variables. The ToString function overrides the ToString function from the Object class to return the Fname value and the Lname value concatenated together.

Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile this code sample. To do this, follow these steps: <ol> Click Project, and then click ProjectName Properties.

Note ProjectName represents the name of the project.</li> Expand Configuration Properties, and then click General.</li> Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting on the right pane, click Apply, and then click OK.</li></ol>

For more information about the common language runtime support compiler options, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

These steps apply to the whole article.le. </li>  Switch to Form1.h[design], and then press F7 to open the Form.h file. Paste the following code in the Form1.h file. Declare a class variable of type Hashtable, and then declare three class variables of type Person class.</li>  Add the following code to the Form1 class: public: Hashtable *MyTable; //For simplicity, create three Person objects to add to the Hashtable collection. Person *Person1,*Person2,*Person3; </li>  To create an instance of the Hashtable object, add the following code in Form1 class constructor after the call for the InitilizeComponent method. MyTable = new Hashtable; </li> In the following steps, use the Add method of the Hashtable object to add three Person objects to the Hashtable object in a try-catch block. The try-catch block catches the exception and displays a message if duplicate keys exist. <ol style="list-style-type: lower-alpha;"> Add a Button control to the Form1 form, and then change the Text property of the Button control to Add Items.</li>  Double-click the button1 control, and then paste the following code in the button1_Click event. Person1 = new Person(S&quot;David&quot;, S&quot;Burris&quot;); Person2 = new Person(S&quot;Johnny&quot;, S&quot;Carrol&quot;); Person3 = new Person(S&quot;Ji&quot;, S&quot;Jihuang&quot;);
 * 1) include &quot;Person.h&quot; </li>

//The Add method takes the key as the first parameter and the value as the second parameter. try {   MyTable->Add(Person1->Lname, Person1); MyTable->Add(Person2->Lname, Person2); MyTable->Add(Person3->Lname, Person3); }

catch (ArgumentException *ae) {   MessageBox::Show(S&quot;Duplicate Key&quot;); MessageBox::Show(ae->Message); } </li></ol> </li> The Hashtable object provides an indexer. In the following steps, index by using the key to access the value that is stored at the hashed location. <ol style="list-style-type: lower-alpha;"> <li>Add a Button control to the Form1 form, and then change the Text property of the Button control to Get Items.</li> <li> Double-click the button2 control, and then paste the following code in the button2_Click event. //Use the indexer of the Hashtable class to retrieve your objects. The indexer takes //the key as a parameter and accesses it by using the hashed location. try {   MessageBox::Show(MyTable->get_Item(Person1->Lname)->ToString); MessageBox::Show(MyTable->get_Item(Person2->Lname)->ToString); MessageBox::Show(MyTable->get_Item(Person3->Lname)->ToString); } catch (NullReferenceException *ex) {   MessageBox::Show(S&quot;Key not in Hashtable&quot;); MessageBox::Show(ex->Message); } </li></ol> </li> <li>In the following steps, use the Remove method to remove a single item from the Hashtable collection. <ol style="list-style-type: lower-alpha;"> <li>Add a Button control to the Form1 form, and then change the Text property of the Button control to Remove Item.</li> <li> Double-click the button3 control, and then paste the following code in the button3_Click event. if (MyTable->Count == 0) {   MessageBox::Show(S&quot;There are no items in HashTable&quot;); } else {   MessageBox::Show(String::Concat(S&quot;The count before removing an Item is &quot;,MyTable->Count.ToString)); MessageBox::Show(S&quot;Removing value stored at key value (Burris)&quot;); //Remove the object that is stored at the key value Person1.Lname. MyTable->Remove(Person1->Lname); } </li></ol> </li> <li>In the following steps, enumerate the items that are stored in the Hashtable collection. <ol style="list-style-type: lower-alpha;"> <li>Add a Button control to the Form1 form, and then change the Text property of the Button control to Enumerate.</li> <li> Double-click the button4 control, and then paste the following code in the button4_Click event. IDictionaryEnumerator *Enumerator;

if (MyTable->Count == 0) {   MessageBox::Show(S&quot;The hashtable is empty&quot;); } else {   MessageBox::Show(S&quot;Enumerating through the Hashtable collection&quot;); Enumerator = MyTable->GetEnumerator; while (Enumerator->MoveNext) {       MessageBox::Show(Enumerator->Value->ToString); } }

ICollection *MyKeys;

if (MyTable->Count == 0) {   MessageBox::Show(S&quot;The hashtable is empty&quot;); } else {   MessageBox::Show(S&quot;Accessing keys property to return keys collection&quot;); MyKeys = MyTable->get_Keys; IEnumerator *Key = MyKeys->GetEnumerator; while(Key->MoveNext) {       String *keyString = __try_cast<String *> (Key->Current); MessageBox::Show(keyString); } } This code declares a variable of type IDictionaryEnumerator and calls the GetEnumerator method of the Hashtable collection. After the code gets Enumerator, the code enumerates through the items in the collection and uses the Keys method of the Hashtable collection to enumerate through the keys. </li></ol> </li> <li>In the following steps, the Clear method is used to clear the Hashtable collection. <ol style="list-style-type: lower-alpha;"> <li>Add a Button control to the Form1 form, and then change the Text property of the Button control to Clear.</li> <li> Double-click the button5 button, and then paste the following code in the button5_Click event. MyTable->Clear; MessageBox::Show(S&quot;HashTable is now empty&quot;); </li></ol> </li> <li>Follow these steps to build and then run the application: <ol style="list-style-type: lower-alpha;"> <li>Press CTRL+SHIFT+S to save the project.</li> <li>Press CTRL+SHIFT+B to build the solution.</li> <li>Press Ctrl + F5 to run the application.</li> <li>Click Add Items.

Notice that three Person objects are added to the Hashtable collection.</li> <li>Click Get Items.

Notice that the indexer obtains the items in the Hashtable collection. The three newly added items appear.</li> <li>Click Remove Item.

Notice that the item at the &quot;Burris&quot; key location is deleted.</li> <li>Click Enumerate.

Notice that the IDictionaryEnumerator interface enumerates through the items in the Hashtable collection, and the Keys property of the Hashtable collection returns a Keys collection.</li> <li>Click Clear.

Notice that all the items are cleared from the Hashtable collection.</li></ol> </li></ol>

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, e-mail address, logo, person, place, or event is intended or should be inferred.

back to the top

Additional query words: Hashtable, HashTable Collection, Hashing, Key, Enumerate, Working with Hashtable.

Keywords: kbhowtomaster kbwindowsforms kbcode KB815673

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.