4

I have a simple enum:

    public enum Status
    {
        sad,
        happy
    };

    protected Status status;

I have successfully binded its values to a combobox:

        cmbStatus.DataSource = Enum.GetValues(typeof(StatusClass.Status));

I now want the selected item/value/index of the combobox to be retrievable. But I am having trouble. I've tried encapsulating the enum, then retrieving its value, like so:

    public Status StatusType
    {
        get { return status; }
        set { stats = value; }
    }

        person.StatusType = cmbStatus.SelectedItem.ToString();

This gives me this error: "Cannot implicitly convert type 'string' to StatusClass.Status.Status'.

I've tried getting the enum names (e.g. 'sad' and 'happy' as text rather than its value) like so (but am not sure how to encapsulate this, nor sure whether it is working):

string statusType = Enum.GetName(typeof(Status), status);

If I can encapsulate this, perhaps I'll solve my issue. I'm stumped at this point; I'm a newbie. Any help's sincerely appreciated. Here's hoping this all makes sense, and gives sufficient information. Thanks.

Lagrange92
  • 51
  • 2

2 Answers2

1

GetValues returns a list of all the values in your enum (sad (0) and happy (1)).

Thus, cmbStatus.SelectedItem already contains the enum value you need, you just need to statically cast it back to the correct type:

person.StatusType = (Status)cmbStatus.SelectedItem;
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

You can parse the value back:

Status status = (Status)Enum.Parse(typeof(Status), "sad");

Or (C# 7):

Enum.TryParse<Status>("sad", true, out Status status);
// Or: Enum.TryParse<Status>("sad", true, out var status);
// Use "status variable" further
JohnyL
  • 6,894
  • 3
  • 22
  • 41
  • `Enum` has `TryParse`? :D ,"once i was blind but now i can see" John chapter 9:25, I noticed you are active, checkout If you have some [extra time](https://stackoverflow.com/q/48005685/7517846) – Djordje Dec 28 '17 at 13:22
  • @Yollo Yes, TryParse with C# 7 fit nice :) I'll take a look at your question. – JohnyL Dec 28 '17 at 13:34
  • @Yollo I have answered to that question – JohnyL Dec 28 '17 at 13:49