Click here to Skip to main content
15,887,453 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi,

I want to knw how to bind combobox with Enum,then what is the datasource,
display member and value member.?????

I just tried with the Code
public Enum MyEnumType
{
     [Description("A")]
     A= 1,
     [Description("B")]
     B= 2,

}
 comboBox2.DataSource = Enum.GetValues(typeof(MyEnumType));
 comboBox1.DisplayMember = "Value"; 
 comboBox1.ValueMember = "Key"; 



Cheers,
ParvathySunu

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 3-Jul-18 21:00pm
v3

You can find somewhat long but a very comprehensive answer in two of my articles:

Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^],
Human-readable Enumeration Meta-data[^].


—SA
 
Share this answer
 
There is an article explaining this here: Data Binding an Enum with Descriptions[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Jun-11 12:49pm    
My 5. The topic of this article is close to the question than that of mine.
--SA
Finally i have got the solution,Its working.....

public Enum MyEnumType
{
[Description("A")]
A= 1,
[Description("B")]
B= 2,
}
Dictionary<string,int> dictionary=new Dictionary<string,>();

foreach (int enumValue in
Enum.GetValues(typeof(MyEnumType)))
{
dictionary.Add(Enum.GetName(typeof(MyEnumType),enumValue),enumValue);
}

ComboBox1.DisplayMember = "Key";;
ComboBox1.ValueMember = "Value";
ComboBox1.DataSource = new BindingSource(dictionary,null);
 
Share this answer
 
public enum MyEnumType
{
[Description("A")]
A= 1,
[Description("B")]
B= 2,
}



private void Form1_Load(object sender, EventArgs e)
{
Dictionary<string, int> dictionary = new Dictionary<string,int>();
foreach (int enumValue in Enum.GetValues(typeof(MyEnumType)))
{
dictionary.Add(Enum.GetName(typeof(MyEnumType), enumValue), enumValue);
}

comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = new BindingSource(dictionary, null);
}
Corrections made above is not a correct one
 
Share this answer
 
Comments
CHill60 4-Jul-18 3:45am    
All you have done is copy the working solution from 7 years ago and put the code into a form load event. In what way do you think this is a solution?
Richard Deeming 5-Jul-18 11:26am    
Plagiarism is not tolerated here. Reporting your account as "abusive/troll".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900