From http://weblogs.asp.net/stevewellens/archive/2009/08/19/how-to-fill-a-listbox-dropdownlist-from-an-enum.aspx, I see this example for assigning enum values to a listbox:
Array Values = System.Enum.GetValues(EnumType);
foreach (int Value in Values)
{
string Display = Enum.GetName(EnumType, Value);
ListItem Item = new ListItem(Display, Value.ToString());
TheListBox.Items.Add(Item);
}
However, in my Windows CE project (.NET 1.1), there is no "System.Enum.GetValues()"; there is "GetUnderlyingType" and "ToObject"...
Is one of those the key to accomplishing this?
UPDATE
Trying to implement Jon Skeet's code, the "ListItem" declaration fails with "The type or namespace name 'ListItem' could not be found (are you missing a using directive or an assembly reference?)"
I am using OpenNETCF. So, VS offers to add "OpenNETCF.Windows.Forms.ListItem" to my using block. But when I do, it then complains on the constructor part of that same line (ListItem item = new ListItem(field.Name, value.ToString());) with: "The best overloaded method match for 'OpenNETCF.Windows.Forms.ListItem.ListItem(string, int)' has some invalid arguments"
The entire handler now is:
private void PrinterPickerForm_Load(object sender, System.EventArgs e)
{
// Got this from Jon Skeet (http://stackoverflow.com/questions/17952900/how-can-i-assign-enum-values-to-a-listbox-in-net-1-1)
Type type = typeof(PrintUtils.BeltPrinterType);
foreach (FieldInfo field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
// Fortunately unboxing to the enum's underlying field type works
int value = (int) field.GetValue(null);
ListItem item = new ListItem(field.Name, value.ToString());
listBoxBeltPrinters.Items.Add(item);
}
}
UPDATE 2
This works:
private void PrinterPickerForm_Load(object sender, System.EventArgs e)
{
Type type = typeof(PrintUtils.BeltPrinterType);
foreach (FieldInfo field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
string display = field.GetValue(null).ToString();
listBoxBeltPrinters.Items.Add(display);
}
}
It's true that the enums themselves are not populating the listboxes, just the strings that represent them, but that's okay, because I have to use a kludgy way to assign the value, too:
private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
//Tried to do something more "el[egant,oquent]" but .NET 1.1 seems to be holding me back
// http://stackoverflow.com/questions/17953173/how-can-i-assign-the-value-selected-in-a-listbox-to-an-enum-var/17953297?noredirect=1#17953297
string sel = listBoxBeltPrinters.SelectedItem.ToString();
if (sel == "Zebra QL220")
{
PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ZebraQL220;
}
else if (sel == "ONiel")
{
PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ONiel;
}
//else if ( . . .)
}