Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Databinding a Hashtable to a drop down list

0 views
Skip to first unread message

Justin Brown

unread,
Jan 1, 2001, 11:01:10 PM1/1/01
to
Does anyone know how to bind a drop down list to a hash table, so that the
displayed option value is equal to the hash value, and the hidden option
value is equal to the hash key (or vice versa)? The DataValueField and
DataTextFields don't seem useful in this situation.....

Thanks!


Mark McEahern

unread,
Jan 12, 2001, 6:32:41 PM1/12/01
to
Please let me know whether this helps...

From the documentation, it looks like you can set the DataSource property of
a DropDownList to anything that supports the IEnumerable interface, which
the HashTable does. The compiler won't complain if you set the DataSource
to a HashTable.

Here's the problem, though: The DataTextField and DataValueField are String
properties that take the name of a field in the DataSource. The HashTable
doesn't have fields, per se. It is a collection of items, each having a key
and a value.

What should you do? One solution is to use a different class to begin with,
such as a DataView. Another option is to add a simple library routine to
your project for converting HashTables to DataViews, such as the following:

Function GetDataView(ByVal ht As Hashtable) As DataView

Dim dt As New DataTable()
Dim dr As DataRow
dt.Columns.Add("key")
dt.Columns.Add("value")
Dim enumerator As IDictionaryEnumerator
enumerator = ht.GetEnumerator()
While (enumerator.MoveNext() = True)
dr = dt.NewRow()
dr("key") = enumerator.Key
dr("value") = enumerator.Value
dt.Rows.Add(dr)
End While
Dim dv As New DataView(dt)
GetDataView = dv

End Function

You might use it like this:

Dim dv as DataView
dv = GetDataView(ht)
With MyDropDownList
.DataSource = dv
.DataTextField = "key"
.DataValueField = "value"
.DataBind()
End With

In the above code snippet, ht refers to your HashTable and MyDropDownList,
of course, refers to your DropDownList.

// Mark


0 new messages