Sort a HashTable

A

Ali

I am binding a hashTable to a dropDownList to pick a State (key: like New
York) and sends the state designation (value: NY) to a filtering procedure.
I have entered the states in the hashTable in alphabetical order, but the
dropDownList renders them in a non-order list.

code snippet:

Dim state as New hashTable
state.Add("Alabama", "AL")
state.Add("Alaska", "AK")
...
state.Add("Wyoming", "WY")
state.Add("Yokon Territory", "YT")

dropDownListState.DataSource = state.keys
dropDownListState.DataBind()

Question 1:
Why does the hashTable items order change in the DropDownList?

Question 2:
Can I sort a hashTable based on the key?

Question 3:
How is a sortedList different from a hashTable?

I am assuming that the hashTable is sorted on the hash, but I am not sure.

Thanks.
Ali
 
C

Cor

Hi Ali,

This is a hash table
Represents a collection of key-and-value pairs that are organized based on
the hash code of the key.

Why do yo not take a collection that is based on the real value of the key
when you want it in that order?

Cor
 
M

Michael Christensen

Hi

I would recommend using a ListDictionary (in
System.Collections.Specialized) if the amount of data is small, and
you need it ordered the way you added it, e.g adding sequential dates
to a dropdownlist (C# code but hope you get the point):

<...>
ListDictionary dates = new ListDictionary();
for (int i = 0; i <= 10; i++)
{
dates.Add(DateTime.Now.AddDays((double)i).ToLongDateString(),i);
}

ddlStartdate.DataSource = dates;
ddlStartdate.DataBind();

<...>

will render something like:

<select name="ddlStartdate" id="ddlStartdate">
<option value="0">27. february 2004</option>
<option value="1">28. february 2004</option>
<option value="2">29. february 2004</option>
<option value="3">1. march 2004</option>
<option value="4">2. march 2004</option>
<option value="5">3. march 2004</option>
<option value="6">4. march 2004</option>
<option value="7">5. march 2004</option>
<option value="8">6. march 2004</option>
<option value="9">7. march 2004</option>
<option value="10">8. march 2004</option>
</select>

In this case it might be easier to use a SortedList though.

Hope this helps.

/Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top