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

后端 未结 2 1154
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条回答
  •  猫巷女王i
    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.

提交回复
热议问题