DotNet Tutorials

Server Intellect

 Hash table using ASP.NET 2.0 and C#

This example illustrates how to create and use a hash table. Each element of hash table is a key/value pair stored in a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be. This example illustrates how to create and use a hash table. Each element of hash table is a key/value pair stored in a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be.

First, you will need to import the using System.Collections  and System.IO namespace.

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

using System.Collection;
using System.IO;

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.

The following example shows how to determine whether the Hashtable contains a specific element.  We can search a hash table either by the keys, or by the associated values; But search by key will make an excellent search efficiency. We use the btnID_Click and btnName_click event to do the work. We then call  the Hashtable.Contains Method to use the collection’s objects’ Equals and CompareTo methods on item to determine whether item exists. In the earlier versions of the .NET Framework, this determination was made by using the Equals and CompareTo methods of the item parameter on the objects in the collection.

public void btnID_Click(Object source, EventArgs e)
{
output.Text = "<PRE>" + HashTableSample.FindEntry(empID.Text, null) + "</PRE>";
btnClear.Visible = true;
}

public void btnName_Click(Object source, EventArgs e)
{
output.Text = "<PRE>" + HashTableSample.FindEntry(0, empName.Text) + "</PRE>";
btnClear.Visible = true;
}

void ResetList()
{
HashTableSample.table.Clear();

HashTableSample.table.Add(5123, "Jay");
HashTableSample.table.Add(2569, "Brad");
HashTableSample.table.Add(1254, "Brian");
HashTableSample.table.Add(6839, "Seth");
HashTableSample.table.Add(3948, "Rajesh");
HashTableSample.table.Add(1930, "Lakshan");
HashTableSample.table.Add(9341, "Kristian");
HashTableSample.table.Add(7921, "Stephen");
HashTableSample.table.Add(2839, "Tom");
HashTableSample.table.Add(1829, "Kit");

MakeList();
}

public void MakeList()
{
lstNames.Items.Clear();

foreach (Object o in HashTableSample.table.Keys)
lstNames.Items.Add(o.ToString() + ": " + HashTableSample.table[o]);
}

class HashTableSample
{
public static Hashtable table = new Hashtable();

public static String FindEntry(Object inKey, Object value)
{
StringWriter strWriter = new StringWriter();
Console.SetOut(strWriter);

Console.WriteLine();

if (inKey == null || inKey == "")
inKey = 0;

Int32 key;
try
{
key = Int32.Parse(inKey.ToString());
}
catch (Exception)
{
key = 0;
}

if (value != null)
{
if (table.ContainsValue(value))
{
Console.WriteLine("Yes, Value '{0}' was found in the list!", value);
}
else
{
Console.WriteLine("Sorry, Employee '{0}' could not be found.", value);
}
}
else
{
if (table.Contains(key))
{
Console.WriteLine("Yes, ID '{0}' was found in the list!", key);
}
else
{
Console.WriteLine("Sorry, Employee ID '{0}' could not be found.", key);
}
}

Console.WriteLine();
Console.WriteLine("Now we will print out the entire list of employees.");

Console.WriteLine("ID\tName");
Console.WriteLine("----\t-----------");

foreach (DictionaryEntry d in table)
{
Console.WriteLine("{0}\t{1}", d.Key, d.Value);
}
return strWriter.ToString();
}
}

The front end  HashtableDemoCsharp.aspx page looks something like this:

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

<table width=800 align="center">
<tr><td width=350><b>Find an existing Entry</b></td>
<td width=150></td>
<td width=150></td>

<td><b>Hashtable Entries</b></td>
<td style="width: 147px"><b>New Entry</b></td>
</tr>

<tr><td width=400>Enter a value (employee name) to find:</td>
<td align=right><asp:textbox width="60px" id="empName" runat="server"/></td>
<td width=200><asp:button width="80px" Text="Find Value" id="btnName" onclick="btnName_Click" runat="server"/>
</td>

<td rowspan=3><asp:ListBox id="lstNames" width="150px" rows="7" runat="server"/></td>

<td align=right style="width: 147px">Key:<asp:textbox width="100px" id="txtAddKey" runat="server"/></td>
</tr>

<tr><td>Enter a key (employee id) to find:</td>
<td align=right><asp:textbox width="60px" id="empID" runat="server"/></td>
<td><asp:button width="80px" Text="Find Key" id="btnID" onclick="btnID_Click" runat="server"/></td>
<td align=right style="width: 147px">Value:<asp:textbox width="100px" id="txtAddVal" runat="server"/></td>
</tr>

<tr><td></td>
<td></td>
<td></td>
<td align=right style="width: 147px">
<asp:button width="120px" Text="Add Entry" id="btnAdd" onclick="btnAdd_Click" runat="server"/>
</td>
</tr>

<tr><td></td>
<td></td>
<td></td>
<td>
<asp:button width="120px" Text="Reset List" id="btnReset" onclick="btnReset_Click" runat="server"/>
</td>
</tr>
</table>

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ResetList();
}
}

void ResetList()
{
HashTableSample.table.Clear();

HashTableSample.table.Add(5123, "Jay");
HashTableSample.table.Add(2569, "Brad");
HashTableSample.table.Add(1254, "Brian");
HashTableSample.table.Add(6839, "Seth");
HashTableSample.table.Add(3948, "Rajesh");
HashTableSample.table.Add(1930, "Lakshan");
HashTableSample.table.Add(9341, "Kristian");
HashTableSample.table.Add(7921, "Stephen");
HashTableSample.table.Add(2839, "Tom");
HashTableSample.table.Add(1829, "Kit");

MakeList();
}

public void MakeList()
{
lstNames.Items.Clear();

foreach (Object o in HashTableSample.table.Keys)
lstNames.Items.Add(o.ToString() + ": " + HashTableSample.table[o]);
}

class HashTableSample
{
public static Hashtable table = new Hashtable();

public static String FindEntry(Object inKey, Object value)
{
StringWriter strWriter = new StringWriter();
Console.SetOut(strWriter);

Console.WriteLine();

if (inKey == null || inKey == "")
inKey = 0;

Int32 key;
try
{
key = Int32.Parse(inKey.ToString());
}
catch (Exception)
{
key = 0;
}

if (value != null)
{
if (table.ContainsValue(value))
{
Console.WriteLine("Yes, Value '{0}' was found in the list!", value);
}
else
{
Console.WriteLine("Sorry, Employee '{0}' could not be found.", value);
}
}
else
{
if (table.Contains(key))
{
Console.WriteLine("Yes, ID '{0}' was found in the list!", key);
}
else
{
Console.WriteLine("Sorry, Employee ID '{0}' could not be found.", key);
}
}

Console.WriteLine();
Console.WriteLine("Now we will print out the entire list of employees.");

Console.WriteLine("ID\tName");
Console.WriteLine("----\t-----------");

foreach (DictionaryEntry d in table)
{
Console.WriteLine("{0}\t{1}", d.Key, d.Value);
}
return strWriter.ToString();
}

public static bool AddEntry(String key, String value)
{
try
{
Int32 i = Convert.ToInt32(key);
table.Add(i, value);
return true;
}
catch (Exception)
{
return false;
}
}
}

public void btnID_Click(Object source, EventArgs e)
{
output.Text = "<PRE>" + HashTableSample.FindEntry(empID.Text, null) + "</PRE>";
btnClear.Visible = true;
}

public void btnName_Click(Object source, EventArgs e)
{
output.Text = "<PRE>" + HashTableSample.FindEntry(0, empName.Text) + "</PRE>";
btnClear.Visible = true;
}

public void btnClear_Click(Object source, EventArgs e)
{
output.Text = "";
empName.Text = "";
empID.Text = "";
btnClear.Visible = false;
}

public void btnReset_Click(Object source, EventArgs e)
{
ResetList();
}

public void btnAdd_Click(Object source, EventArgs e)
{
if (txtAddKey.Text == "" || txtAddVal.Text == "")
{
output.Text = "ADD FAILED: Please ensure you enter both a key, and value entry";
btnClear.Visible = true;
}
else
{
if (HashTableSample.AddEntry(txtAddKey.Text, txtAddVal.Text))
{
MakeList();
btnClear_Click(null, null);
}
else
{
output.Text = "ADD FAILED: Please ensure the following:<br>" +
"1) The key is a valid integer<br>" +
"2) The key does not already exist in the list";
btnClear.Visible = true;
}
}
}
}

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.



Looking for the VB.NET2005 Version? Click Here!


Looking for more ASP.NET Tutorials? Click Here!

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 
123 ASP

411 ASP

Dot Net Freaks

Server Intellect