Hashtable in C#

Hashtable is used for store information based on key/value pairs. Hashtable class is defined in the System.Collections namespace.

Example: 

Form Design:
mple form for hashtable example
Sample form for hashtable example
Note:  You need to import two namespaces:
       using System;
     using System.Collections;
Code behind: 
        Hashtable ht = new Hashtable();
        private void Form1_Load(object sender, EventArgs e)
        {
           
            ht.Add("001", "computer");
            ht.Add("002", "laptop");
            ht.Add("003", "ipad 2");
            ht.Add("004", "ipad  3");
            ht.Add("005", "ipad 4");
            ht.Add("006", "iphone 4");
            ht.Add("007", "iphone 4s");
            ht.Add("008", "iphone 5");
            ht.Add("009", "sumsung galaxy S");
            ht.Add("010", "sumsung galaxy SI");
            ht.Add("011", "sumsung galaxy SII");
            ht.Add("012", "sumsung galaxy SIII");
            ICollection keys = ht.Keys;
            foreach (string ind in keys)
            {
                listBox1.Items.Add(ind + " : " + ht[ind]);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
           //check whether the hashtable contain value : Sumsung Galaxy Tab
            if (ht.ContainsValue("Sumsung Galaxy Tab"))
            {
                label1.Text = "Sumsung Galaxy Tab is already in the list";
            }
            else
            {
                ht.Add("014", "Sumsung Galaxy Tab");
            }       
            //check whether the hashtable contain key : 013
            if (ht.ContainsKey("013"))
            {
                label2.Text = "013 is already in the list";
            }
            else
            {
                ht.Add("013", "Mac Book air");
            }                    
        }
Result:

Hope this post is helpful.
Hashtable in C# Hashtable in C# Reviewed by BeiLover on 5:07 PM Rating: 5

No comments:

Powered by Blogger.