Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » C# Language » Understanding HashTable in C# and .NET

Understanding HashTable in C# and .NET

A collection object is used to store generic data types and HashTable is a collection that is used to store a value and key pair objects. This article shows how to use the HashTable class in .NET to do the same.

Author Rank :
Page Views : 165194
Downloads : 1066
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HashTable.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



Collections are used to store generic data types. Some of the collection classes available in .NET Framework includes ArrayList, HashTable, Stack, and Queue.
In this article, I am going to explain the Hashtable class and how to use it. The Hashtable object contains items in key/value pairs. The keys are used as indexes. We can search value by using their corresponding key. Items are added to the Hashtable with the Add() method. The data type of Hashtable is object and the default size of a Hashtable is 16.

In this article, I am using a program to define and use a Hashtable object.

First of all, I created a class library and in this class library have a class that has two properties named as Roll and Name. I am saving these roll number and name in this class. Now I will use to store these in a Hashtable.

My class name is called HashTableClass, that is listed as following:
using System;
using System.Collections.Generic;
using System.Text; 

namespace HashTableClass

{

    public class Class1

    {

        int rollno;

        string name;

 

        public int Roll

        {

            get { return rollno; }

            set { rollno = value; }

        }

 

        public string Name

        {

            get { return name; }

            set { name = value; }

        }

    }
}

Now I create an application that will use my class library and add my DLL reference to my application.

AddReference.jpg

Figure 1.

Add this namespace to use Hashtable.

using System.Collections;

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.

Now here is my application class.


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Collections;

 

namespace AHashTablePresentation

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        int  b = 1, key,j=0;

        Hashtable ht = new Hashtable();

 

        private void Button_Click(object sender, EventArgs e)

        {

        }

 

        //To Search a perticular Record

        private void button6_Click(object sender, EventArgs e)

        {

            j = Int32.Parse(textBox3.Text);

            HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);

            textBox1.Text = obj.Roll.ToString();

            textBox2.Text = obj.Name;

        }

 

        //To Add a Record

        private void AddRecord_Click_1(object sender, EventArgs e)

        {

            HashTableClass.Class1 obj = new HashTableClass.Class1();

            obj.Roll = Int32.Parse(textBox1.Text);

            obj.Name = textBox2.Text;

            key = b;

            ht.Add(key, obj);

            b = b + 1;

            textBox1.Text = "";

            textBox2.Text = "";

        }

 

        //To Reach on First Record

        private void FirstRecord_Click(object sender, EventArgs e)

        {

            if (j == 1)

            {

                MessageBox.Show("You All Ready first Record");

            }

            else

            {

                j = 1;

                HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);

                textBox1.Text = obj.Roll.ToString();

                textBox2.Text = obj.Name;

            }

        }

 

        //To Reach on Next Record

        private void NextRecord_Click(object sender, EventArgs e)

        {

            if (j == ht.Count)

            {

                MessageBox.Show("You All Reday Last Record");

            }

            else

            {

                j = j + 1;

                HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);

                textBox1.Text = obj.Roll.ToString();

                textBox2.Text = obj.Name;

            }

        }

 

        // To Reach on Previous Record

        private void Previous_Click(object sender, EventArgs e)

        {

            if (j == 1)

            {

                MessageBox.Show("You All Ready On First Record ");

            }

            else

            {

                j = j - 1;

                HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);

                textBox1.Text = obj.Roll.ToString();

                textBox2.Text = obj.Name;

            }

        }

 

        //To Reach on Last Record

        private void Last_Click(object sender, EventArgs e)

        {

            if (j == ht.Count)

            {

                MessageBox.Show("AlReady At Last");

            }

            else

            {

                j = ht.Count;

                HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);

                textBox1.Text = obj.Roll.ToString();

                textBox2.Text = obj.Name;

            }

        }

    }

}

When user run the application then the window will become look like as:

Image1.jpg

Figure 2: By clicking AddRecord button we can add the record in Hashtable.

Image2.jpg

Figure 3: After adding the record if user want to see the record by passing the key in textbox.

Image3.jpg

Figure 4: If user click on first record.

Image4.jpg

Figure 5: If user click on next record.

Last.jpg

Figure 6: If user click on last record.

LastAgain.jpg

Figure 7: If user is on last record and he/she click again on last then a message box will show the message that you allready on last record. This functionality is also in first, next, previous button.

Previous.jpg

Figure 8: If user  click on previous record.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application. With programming he loves photography, traveling and reading books.
(Talabpur*)
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
hashtable by soumya On March 10, 2008
Iam getting an exception "Unable to cast object of type 'System.String' to type 'hashtableclass.Class1" for the line HashTableClass.Class1 obj = (HashTableClass.Class1)(ht[j]);
Reply | Email | Modify 
hashtable for treeview by vidushi On October 23, 2008
how can hashtable help me in treeview(have two select multi nodes from one tree and place them in another)?
Reply | Email | Modify 
hash table by srinivas On December 25, 2009
nice example and application
Reply | Email | Modify 
asdas by debadatta On October 14, 2010
asasasd
Reply | Email | Modify 
This is Good exp by suresh On January 5, 2011
Hi Friend ..... this is very good code and very helpful for making projects
Reply | Email | Modify 
thank you by kathir On February 24, 2011
I clearly understood from your code about hash table thank you
Reply | Email | Modify 
hashtable by sravanti On February 28, 2012
nice
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.