Combobox

  • Thread starter Thread starter Jim Heavey
  • Start date Start date
J

Jim Heavey

I thought I could create a "ListViewItem" and then bind that item to a
combox box, but perhaps that is was with an ASP.Net control. When I create
a listViewItem and bind it to a combo box, it does bind, but what show up
is something like ListViewItem{MyField}.

So if I have a hastable, what mechanism would I use to create a bindable
object such that I can define the "ValueMember" and "DisplayMember"?

Thanks in advance for your assistance!!!!!!!!!
 
Complex DataBinding accepts as a data source either an IList or an
IListSource. So you can't bind a HashTable directly to a ComboBox.

The following code shows a work-around:
Dim myHashTable as new System.Collections.Hashtable()

myHashTable("GA") = "Georgia"
myHashTable("FL") = "Florida"
myHashTable("AL") = "Alabama"

For each Item in myHashTable
Dim newListItem as new ListItem()
newListItem.Text = Item.Value
newListItem.Value = Item.Key
DropDownList1.Items.Add(newListItem)
Next

http://www.devcity.net/net/article.aspx?alias=aspnet_dropdown
 
Jim,

The dropdown control can take a ListViewItem object as a parameter to the
Items.Add() method but it only uses the Text property when adding it. The
ListViewItem is only full used by ListBox class.

I'm not sure why you are trying to use binding instead of a loop with calls
the DropDownList.Add() method but, keep in mind the nature of binding. All
objects can be bound to most controls, however some controls simply call the
ToString() method if the object does not support the IEnumarable interface.

Simply put the most common use of binding is to set the DataSource property
to a collection or array. Then set the other Data...Field propertys with
the field names. Then when the DataBind() method is called the control loops
through the DataSource object using the IEnumerable interface and uses
reflection to load the control with the Data Fields specified.
Note: Binding is always slower than Adds due to the use of reflection.

With that said, since a Hashtable class supports the IEnumerable interface
you can do the following: Set the DropDownList.DataSource property to the
Hashtable object, Set the DropDownList.DataTextField property to "Value" as
in the IDictionaryEnumerator.Value, Set the DropDownList.DataValueField
property to "Key" as in the IDictionaryEnumerator.Key.

One thing of note is that when loading the Value object, from the Hashtable,
will have it's ToString() method called. This is why when you bound the
ListViewItem, you saw the text you did.

For more information on C# Controls look at the MSDN help and look for the
"DropDownList class" and the "Hashtable class" in the index. Each method
and property are described in detail.

A little long winded but hope this helps.
 
Back
Top