Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Work with HashTable using Csharp and ASP.NET

In this article we will cover the common features of HashTable with c# and asp.net

Introduction:

HashTable is a collection which store Key and Value combination inside. After adding the key, the HashTable internally calculate a hash code corresponding to each key. This Hash code later used to find the elements quickly.

This article will cover the following functionality:

  1. Add Item in HashTable
  2. Remove Item from HashTable
  3. Clear HashTable
  4. Count HashTable Items
  5. Key Exist in HashTable
  6. Value Exist in HashTable
  7. Loop Each Item of HashTable
  8. Clone HashTable

ASP.NET Code:

This article has some ASP.Net components to fully demonstrate the functionality of HashTable. The following controls are used.

  1. A ListBox, TextBox and Label
  2. Some Buttons for Functionality

Listing 1: ASP.NET Code Snippet

<head runat="server">
    <title>MrBool.com - HashTable Tutorial</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox Style="background-color: #669999; color: White" ID="ListBoxCloths" runat="server"
            Height="200px" Width="300px"></asp:ListBox>
        <br />
        <br />
        Key:
        <asp:TextBox ID="txtKey" runat="server" Width="100px"></asp:TextBox>
        Value:
        <asp:TextBox ID="txtValue" runat="server" Width="100px"></asp:TextBox>
        <br />
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </div>
    <br />
    <br />
    <asp:Button runat="server" ID="btnReload" Text="Reload" OnClick="btnReload_Click" />
    <asp:Button runat="server" ID="btnAdd" Text="Add" OnClick="btnAdd_Click" />
    <asp:Button runat="server" ID="btnRemove" Text="Remove" OnClick="btnRemove_Click" />
    <asp:Button runat="server" ID="btnClear" Text="Clear" OnClick="btnClear_Click" />
    <br />
    <asp:Button runat="server" ID="btnCount" Text="Count Items" OnClick="btnCount_Click" />
    <asp:Button runat="server" ID="btnKeyExist" Text="Key Exist" OnClick="btnKeyExist_Click" />
    <asp:Button runat="server" ID="btnValueExist" Text="Value Exist" OnClick="btnValueExist_Click" />
    <br />
    <asp:Button runat="server" ID="btnLoopThrough" Text="Loop Through" OnClick="btnLoopThrough_Click" />
    <asp:Button runat="server" ID="btnClone" Text="Clone" OnClick="btnClone_Click" />
    </form>
</body>
HashTable Data in ListBox

Figure 1: HashTable Data in ListBox

C# Code:

Let’s discuss the C# code to implement the above functionalities. Before going to core functionality, you have to include the following namespaces:

using System.Collections;

After including the above namespace define a static HashTable globally, So that we can use it throughout the application.

static Hashtable ClothsHashTable;

Now we have to fill this hashtable with some data. We are using some apparel data to demonstrate this functionality.

Listing 2: C# Code to Fill HashTable

private void FillHashtable()
    {
        ClothsHashTable = new Hashtable();
        ClothsHashTable.Add("Key1", "Shirt");
        ClothsHashTable.Add("Key2", "Pant");
        ClothsHashTable.Add("Key3", "Jeans");
        ClothsHashTable.Add("Key4", "Shorts");
        ClothsHashTable.Add("Key5", "Jacket");
        ClothsHashTable.Add("Key6", "T-Shirt");
        ClothsHashTable.Add("Key7", "Underwear");
        ClothsHashTable.Add("Key8", "Top");

    }

Add Item in HashTable:

HashTabe items are key-value pair, so to add the item you should have a unique key and a value. Before adding a pair to hashtable just check if key already exist and if exist do not insert it otherwise it will through a exception. The below program will automatically add the key if user will not provide it.

HashTable Key-Value Pair Added (Key10, Cap)

Figure 2: HashTable Key-Value Pair Added (Key10, Cap)

Listing 3: C# HashTable - Add Item

protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (txtValue.Text.Trim() != "")
        {
            string strKey = "";
            if (txtKey.Text.Trim() == "")
                strKey = "Key" + (ClothsHashTable.Keys.Count + 1);

            if (!ClothsHashTable.ContainsKey(strKey))
            {
                ClothsHashTable.Add(strKey, txtValue.Text.Trim());

                ListBoxCloths.DataSource = ClothsHashTable;
                ListBoxCloths.DataBind();
                lblMessage.Text = "Hashtable Item Added";
            }
            else
            {
                lblMessage.Text = "Key Already Exist, Enter Another Key";
            }

        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Add";
        }

    }

Remove Item from HashTable:

As compare to ArrayList, HashTable has only one way to delete an item, Take a key pass it and delete the item.

HashTable Key-Value Pair Deleted (Key4, Shorts)

Figure 3: HashTable Key-Value Pair Deleted (Key4, Shorts)

Listing 4: C# HashTable - Delete Item

protected void btnRemove_Click(object sender, EventArgs e)
    {
        if (txtKey.Text.Trim() != "")
        {
            if (ClothsHashTable.Contains(txtKey.Text.Trim()))
            {
                ClothsHashTable.Remove(txtKey.Text.Trim());
                ListBoxCloths.DataSource = ClothsHashTable;
                ListBoxCloths.DataBind();

                lblMessage.Text = "HashTable Item Deleted";
            }
            else
            {
                lblMessage.Text = "Item Not Found.";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter Key to Delete Item";
        }
    }

Clear HashTable:

HashTable provide a Clear() method to clear all the items. The below snippet will help you to understand the clear implementation.

Listing 5: C# HashTable - Clear Items

protected void btnClear_Click(object sender, EventArgs e)
    {
        ClothsHashTable.Clear();
        ListBoxCloths.DataSource = ClothsHashTable;
        ListBoxCloths.DataBind();
        lblMessage.Text = "HashTable Items Cleared";
    }

Count HashTable Items:

HashTable provide a “Count” property to count all items present. This is very useful and popular property. The count is also useful while looping though all the items.

HashTable Count Items - 8

Figure 4: HashTable Count Items - 8

Listing 6: C# HashTable - Count Items
protected void btnCount_Click(object sender, EventArgs e)
    {
        int intCount = ClothsHashTable.Count;
        lblMessage.Text = "HashTable Items Count:" + intCount;
    }

Key Exist in HashTable:

Key play a very important role in case of hashtable. Before adding an item into hashtable you have to verify that key is not already present. Key should be unique. HashTable provide a method “ContainsKey” to check if key already exist.

HashTable Find Key - Key5

Figure 5: HashTable Find Key - Key5

Listing 7: C# HashTable - Find Key

protected void btnKeyExist_Click(object sender, EventArgs e)
    {
        if (txtKey.Text.Trim() != "")
        {
            if (ClothsHashTable.ContainsKey(txtKey.Text.Trim()))
            {
                lblMessage.Text = "The Key " + txtKey.Text.Trim() + " Found in HashTable";
            }
            else
            {
                lblMessage.Text = "The Key " + txtKey.Text.Trim() + " Not Found in HashTable";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter Key";
        }
    }

Value Exist in HashTable:

HashTable provide “ContainsValue”method to find a value. This is important method to search for a value in hashtable. Note that the below searching do not require any role of key.

 HashTable Find Value - Shirt

Figure 6: HashTable Find Value - “Shirt”

Listing 8: C# HashTable - Find Value

protected void btnValueExist_Click(object sender, EventArgs e)
    {
        if (txtValue.Text.Trim() != "")
        {
            if (ClothsHashTable.ContainsValue(txtValue.Text.Trim()))
            {
                lblMessage.Text = "The Value " + txtValue.Text.Trim() + " Found in HashTable";
            }
            else
            {
                lblMessage.Text = "The Value " + txtValue.Text.Trim() + " Not Found in HashTable";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter Value";
        }

    }

Loop Each Item of HashTable:

Many times you require to check all the items of hashtable using for loop. The below code snippet will help you to loop through all the items of hashtable.

The hashtable internally use the dictionary, so find dictionary item and then get the corresponding key and value.

Listing 9: C# HashTable - Traverse all Items

protected void btnLoopThrough_Click(object sender, EventArgs e)
    {
        foreach (DictionaryEntry DE in ClothsHashTable)
        {
            lblMessage.Text += ", " + DE.Key + "   -   " + DE.Value;
        }
        lblMessage.Text = lblMessage.Text.TrimStart(',');

    }

Clone HashTable:

HashTable clone method provides a shallow copy. Shallow copy means copy the object values and not their reference. In other word if you change the copied data it will reflect at original place also.

Listing 10: C# HashTable - Clone

protected void btnClone_Click(object sender, EventArgs e)
    {
        Hashtable hsShallowCopy = (Hashtable)ClothsHashTable.Clone();

        foreach (DictionaryEntry DictionaryItem in hsShallowCopy)
        {
            lblMessage.Text += ", " + DictionaryItem.Key + "   -   " + DictionaryItem.Value;
        }
        lblMessage.Text = lblMessage.Text.TrimStart(',');
    }

Conclusion:

We have covered the common features of HashTable, Please feel free to ask your questions and comment below.

You can go through the source of the code and try different operations with HashTable.



I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login