In vb.net / winforms, how can a hashtable be bound to a drop down list or any other datasource-driven control?
Just use the dropdown lists's Datasource property
DropDownList dd = new DropDownList();
Hashtable mycountries = New Hashtable();
mycountries.Add("N","Norway");
mycountries.Add("S","Sweden");
mycountries.Add("F","France");
mycountries.Add("I","Italy");
dd.DataSource=mycountries;
dd.DataValueField="Key";
dd.DataTextField="Value";
dd.DataBind();
myCtrl.DataSource = myHashtable
myCtrl.DataBind()
Example source of bindable control:
<itemtemplate>
<%# DataBinder.Eval(Container.DataItem, "Key", "<td>{0}</td>") %>
<%# DataBinder.Eval(Container.DataItem, "Value", "<td>${0:f2}</td>") %>
</itemtemplate>
-Oisin
Is this winforms, wpf, or asp.net? [update: ahh... winforms ;-p]
winforms wants data to be IList
(or, indirectly, via IListSource
) - so I'm guessing (from the comment) that you are using winforms. None of the inbuilt dictionary-like collections implement IList
, but to be honest it doesn't matter: if you are data-binding, the volume is probably fairly small, so a regular list should be fine.
The best option is something like a List<T>
or BindingList<T>
, where T
has all the properties you want to bind to. Is this an option? If you are stuck with 1.1 (since you mention HashTable
rather than Dictionary<,>
), then use ArrayList
.
Example (in C#):
class MyData
{
public int Key { get; set; }
public string Text { get; set; }
}
[STAThread]
static void Main()
{
var data = new List<MyData>
{
new MyData { Key = 1, Text = "abc"},
new MyData { Key = 2, Text = "def"},
new MyData { Key = 3, Text = "ghi"},
};
ComboBox cbo = new ComboBox
{
DataSource = data,
DisplayMember = "Text",
ValueMember = "Key"
};
cbo.SelectedValueChanged += delegate {
Debug.WriteLine(cbo.SelectedValue);
};
Application.Run(new Form {Controls = {cbo}});
}
Example for a given object called Order:
List<Order> list = new List<Order>{};
foreach (Order o in OOS.AppVars.FinalizedOrders.Values)
{
list.Add(o);
}
this.comboBox_Orders.DataSource = list;
this.comboBox_Orders.DisplayMember = "Description";
What's cool about this is that you can then get the data back out of the list as the original object (not just the value field as in asp.net).
Order order = (Order)this.comboBox_Orders.SelectedValue;
And, if you happen to use Dictionary as the datasource, you can use
MyDDL.Datasouce = myDict.ToList();
and it will convert it to a list type.