Hash table represents a collection of key/value pairs that are organized based on the hash code of the key. Hash tables are used to store data in ASP.NET similar to dataset or datatable but Hash tables store data as key value pairs.
In below example we are going to store some data into a hash table and read them back.
Our key value is a string and our value is a Student type object.
First let's create the student class.
public class Student
{
public string StudentID { get; set; }
public string StudentName { get; set; }
public string Subject { get; set; }
}
Now Store Data in the hash table.
private Hashtable getHashTable()
{
Hashtable itemList = new Hashtable();
Student st = new Student() { StudentID="1",StudentName="Chamara",Subject="Maths"};
Student st2 = new Student() { StudentID = "2", StudentName = "Janaka", Subject = "Science" };
itemList.Add("1", st);
itemList.Add("2", st2);
return itemList;
}
We have stored two student type instances in our hash table. Below code will loop through each student type object and print them on the screen.
private void ReadHashTable()
{
Hashtable itemList = new Hashtable();
itemList = getHashTable();
foreach (DictionaryEntry item in itemList)
{
Student StItem = (Student)item.Value;
Response.Write(StItem.StudentID + "<br/>");
Response.Write(StItem.StudentName + "<br/>");
Response.Write(StItem.Subject + "<br/>");
Response.Write("/*...........*/");
Response.Write("<br/>");
}
}
Out put:
1
Chamara
Maths
/*...........*/
2
Janaka
Science
/*...........*/
Chamara
Maths
/*...........*/
2
Janaka
Science
/*...........*/
No comments:
Write comments