18

How do i show enum values in a combo-box? The code below result in the combobox having all displayed names being "caseHandler.cState". I wanted it to have the actual names of the enum values.

My enum is defined as follows:

public enum caseState { Active = 1, Finished, Problem } 

I have a class that is defined as this:

public class cState { public string _name; public int _id; public cState(int id,string name) { _name = name; _id = id; } } 

And the code for populating my combobox:

ArrayList AL = new ArrayList(); foreach (string cs in Enum.GetNames(typeof(caseState))) { cState aEnum = new cState((int)Enum.Parse(typeof(caseState),cs),cs); AL.Add(aEnum); } cbState.DisplayMember = "_name"; cbState.ValueMember = "_id"; cbState.DataSource = AL; 
1

2 Answers 2

32

Have you tried to use

cbState.DataSource = Enum.GetNames(typeof(caseState)); 

And when retrieving data just Parse it

Sign up to request clarification or add additional context in comments.

2 Comments

@ Stecya - this worked. But can you explain to me why the code i've written doesn't work?
@ Stecya - ok, i found the mistake. I should've implemented _name and _id as properties, then it would have worked.
4

Here My Code , you can have text and value together and fill Combobox

 public enum LayerType : int { [Description("محوطه")] Area = 1, [Description("ساختمان")] Building = 2, [Description("بارانداز")] Wharf = 3,} drpLayer.DataSource = Enum.GetValues(typeof(LayerType)) .Cast<Enum>() .Select(value => new { (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description, value }) .OrderBy(item => item.value) .ToList(); drpLayer.DisplayMember = "Description"; drpLayer.ValueMember = "value"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.