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

后端 未结 2 1152
Happy的楠姐
Happy的楠姐 2020-12-12 07:47

I want to avoid the kludginess of:

private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
    string sel = string listBox         


        
相关标签:
2条回答
  • 2020-12-12 08:20

    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;
    }
    
    0 讨论(0)
  • 2020-12-12 08:22

    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.

    0 讨论(0)
提交回复
热议问题