1

My problem is that I have a combo box filled with units such as length or weight ie. Inches, Feet, Yard. Or Oz, Lb, Ton. Anyways I have enums such as

public enum Torques {

    /// <remarks/>
    DyneCentimeters,

    /// <remarks/>
    FootPounds,

    /// <remarks/>
    InchPounds,

    /// <remarks/>
    KilogramMeter,

    /// <remarks/>
    MeterNewtons,
}

I need an elegant way of grabbing the value out of the drop down and creating a variable of the matching enum type. Right now I am using a case statement such as

 Computers fromUnit = Computers.Bit;
            switch (compFromUnit.Text)
            {
                case "Bit":
                    fromUnit = Computers.Bit;
                    break;
                case "Byte":
                    fromUnit = Computers.Byte;
                    break;
                case "Kilobyte":
                    fromUnit = Computers.Kilobyte;
                    break;
                case "Megabyte":
                    fromUnit = Computers.Megabyte;
                    break;
                case "Gigabyte":
                    fromUnit = Computers.Gigabyte;
                    break;
                case "Terabyte":
                    fromUnit = Computers.Terabyte;
                    break;
                case "Petabyte":
                    fromUnit = Computers.Petabyte;
                    break;
                default:
                    fromUnit = Computers.Bit;
                    break;
            }

Some of my lists are quite lengthy and to complete the project in this manner would call for some very long case statements. I know there must be some way of completing this all in one line of code.

When I try to assign a value to a selection such as combo.selected.Text = "Bit" combo.selected.Value = "Computers.Bit" and then say something like toUnit = combo.selected.value is says it cannot convert from string.

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

If you're positive that the string values in the ComboBox drop-down exactly match your enum values (as seems to be the case in your example), you could use Enum.Parse:

var userSelection = (Computers)Enum.Parse(typeof(Computers), compFromUnit.Text);

If there's any chance they won't match exactly, use Enum.TryParse instead:

Computers userSelection;

if (!Enum.TryParse(compFromUnit.Text, out userSelection))
{
    // You've got a value that doesn't exist in the Enum... do something
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Thanks Grant, I knew there had to be a simple solution, that is the whole reason for these languages. I really appreciate the quick and very useful response. It worked like a charm :) – user3042911 Nov 27 '13 at 18:25
0

Enum.TryParse would suit your needs here.

Computers fromUnit;
var succes = Enum.TryParse(compFromUnit.Text, out fromUnit);

if(!succes)
{
    // Invalid string value
}
Koen
  • 2,501
  • 1
  • 32
  • 43