1

I've followed the advice given here : How to bind Enum to combobox with empty field in C# but it gave me some unusable content:

Result

which is not what I would like to see... Here's the code I used to bind:

comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true); 

And here's the background:

public enum MessageLevel { [Description("Information")] Information, [Description("Warning")] Warning, [Description("Error")] Error } ---- public static string GetEnumDescription(string value) { Type type = typeof(MessageLevel); var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault(); if (name == null) { return string.Empty; } var field = type.GetField(name); var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name; } public static List<object> GetDataSource(Type type, bool fillEmptyField = false) { if (type.IsEnum) { var data = Enum.GetValues(type).Cast<Enum>() .Select(E => new { Key = (object)Convert.ToInt16(E), Value = GetEnumDescription(E.ToString()) }) .ToList<object>(); var emptyObject = new { Key = default(object), Value = "" }; if (fillEmptyField) { data.Insert(0, emptyObject); // insert the empty field into the combobox } return data; } return null; } 

How can I make a correct binding and adding one empty entry?

7
  • Try to set DisplayMemberPath="Value" and SelectedValuePath="Key" Commented Sep 25, 2015 at 11:24
  • @Michael as it's winform (mea culpa, I didn't tag it at first) it's DisplayMember and ValueMember. If you want some rep... :) Commented Sep 25, 2015 at 11:34
  • What is the purpose of GetEnumDescription()? It seems to try to access an attribute in the enum value. Commented Sep 25, 2015 at 11:34
  • @Ian yeah, I've pasted an old version of the enum, it's now fixed Commented Sep 25, 2015 at 11:36
  • @Thomas thanks, was thinking it's WPF. Commented Sep 25, 2015 at 11:38

1 Answer 1

1

So the solution is to also set DisplayMember and ValueMember properties on ComboBox, so that it will know how to treat Key and Value properties.

comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true); comboBox2.DisplayMember = "Value"; comboBox2.ValueMember = "Key"; 
Sign up to request clarification or add additional context in comments.

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.