How can I assign the value selected in a listbox to an enum var?

你说的曾经没有我的故事 提交于 2019-12-17 21:23:54

问题


I want to avoid the kludginess of:

private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
    string sel = string listBoxBeltPrinters.SelectedItem.ToString();
    if (sel == "Zebra QL220")
    {
        PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ZebraQL220;
    }
    else if (sel == "ONiel")
    {
        PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ONiel;
    }
    else if ( . . .)
}

Is there a way I can more elegantly or eloquently assign to an enum based on a list box selection, something like:

PrintUtils.printerChoice = listBoxBeltPrinters.SelectedItem.ToEnum(PrintUtils.BeltPrinterType)?

?


回答1:


You could try something like this

Array values = Enum.GetValues(typeof(BeltPrinterType));//If this doesn't help in compact framework try below code
Array values = GetBeltPrinterTypes();//this should work, rest all same
foreach (var item in values)
{
    listbox.Items.Add(item);
}

private static BeltPrinterType[] GetBeltPrinterTypes()
{
    FieldInfo[] fi = typeof(BeltPrinterType).GetFields(BindingFlags.Static | BindingFlags.Public);
    BeltPrinterType[] values = new BeltPrinterType[fi.Length];
    for (int i = 0; i < fi.Length; i++)
    {
        values[i] = (BeltPrinterType)fi[i].GetValue(null);
    }
    return values;
    }

private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
    if(!(listBoxBeltPrinters.SelectedItem is BeltPrinterType))
    {
        return;
    }
    PrintUtils.printerChoice = (BeltPrinterType)listBoxBeltPrinters.SelectedItem;
}



回答2:


With Enum.Parse you could convert from a string to a Enum.

PrintUtils.printerChoice = (PrintUtils.BeltPrinterType)Enum.Parse(typeof(PrintUtils.BeltPrinterType),listBoxeltPrinters.SelectedItem);

Also there is method Enum.TryParse which returns a bool indicating if the parse is succeeded.



来源:https://stackoverflow.com/questions/17953173/how-can-i-assign-the-value-selected-in-a-listbox-to-an-enum-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!