Using Hashtable and SortedList

Posted by Neeks under ASP.NET category on | Views : 4286
Your ASPX Page.
<form id="form1" runat="server">
<asp:DropDownList runat="server" ID="ddlHashtable"></asp:DropDownList>
<asp:DropDownList runat="server" ID="ddlSorted"></asp:DropDownList>

Your Code file

protected void Page_Load(object sender, EventArgs e)
Hashtable has = new Hashtable();
//You can add new entry in the Hastable using Hashtable.Add(...) method
has.Add("B", "Bombay");
has.Add("D", "Delhi");
has.Add("A", "Ahmedabad");
has.Add("S", "Surat");
//Here we are asignig the value directly to the Dropdownlist.

//Method - 1 :To assign the data to DropDown. [ Give direct Datasource as Hashtable ]
ddlHashtable.DataSource = has;
ddlHashtable.DataTextField = "Value";
ddlHashtable.DataValueField = "Key";

//Method - 2 :Fill the datasource of dropdown list using the Loop and ListItem object
IDictionaryEnumerator dictionary = has.GetEnumerator();
while (dictionary.MoveNext())
//Read the Hastable using dictionary object
ListItem item = new ListItem(dictionary.Value.ToString(), dictionary.Key.ToString());

//Assigning the value directly to the variable or contrl.
string strTest = has["A"].ToString();
Response.Write(strTest); // You can directly display the value as Response.Write(has["A"].ToString());

//You can use SortedList object same as Hastable.
SortedList sl = new SortedList();
sl.Add("B", "Bombay");
sl.Add("D", "Delhi");
sl.Add("A", "Ahmedabad");
sl.Add("S", "Surat");
ddlSorted.DataSource = sl;
ddlSorted.DataTextField = "Value";
ddlSorted.DataValueField = "Key";

Comments or Responses

Login to post response