[2005] Binding listbox to hashtable
In an ASP.net application, i was able to create a hashtable, and bind a dropdownlist to it:
C# Code:
DropDownList1.DataSource = myHashTable;
DropDownList1.DataTextField = "Key";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
this worked successfully.
When I tried it in a winforms app, binding a listbox to a hashtable:
C# Code:
ListBox1.DataSource = myHashTable;
ListBox1.DisplayMember = "Key";
ListBox1.ValueMember = "Value";
I got an error saying that complex databinding requires an implementation of IList or IListSource as a datasource.
What am i doing wrong?
Re: [2005] Binding listbox to hashtable
Try this:
c# Code:
// Add my hash to the listbox.
this.listBox1.DisplayMember = "Key";
this.listBox1.ValueMember = "Value";
foreach (DictionaryEntry ent in myHash)
{
this.listBox1.Items.Add(ent);
}
Re: [2005] Binding listbox to hashtable
Data-binding in WebForms requires an object whose type implements the IEnumerable interface, which the Hashtable class does. In WinForms the object must implement the IList or IListSource interface, which Hastable does not. IList inherits IEnumerable and is thereofre more specific, while IListSource has a property that returns an IList.
As for nmadd's advice, that won't work because the DisplayMember and ValueMember properties only have an effect if the control is data-bound.
You simply cannot bind a Hashtable in WinForms. You will have to do without data-binding or else create your own class to wrap the Hashtable that does implement IList or IListSource.
Re: [2005] Binding listbox to hashtable
Thanks for the clarification jmc. Good as usual. :thumb: