Data Binding to an Enumeration

Tuesday, November 13, 2007

Paul Stovell gets development questions and he’s not afraid to answer them. “I recieved an email this morning as from Steve Pietrek, a Delphi programmer moving to .NET (great choice Steve!). His question essentially asked how would he go about binding a Windows Forms ComboBox to an enumeration such as this:

public enum CustomerType {
Type1 = 1,
Type2 = 2,
Type3 = 3
}

Fortunately, I figured out how to do this in Trial Balance about a week ago, so I thought I’d share my approach here.

The values in an enumeration (Type1, Type2, Type3 in this case) are all exposed as members on the enumeration type, which means we can use .NET reflection to retrieve them:

private List ConvertEnumForBinding(System.Enum enumeration) {
List results = new List();

// Use reflection to see what values the enum provides
MemberInfo[] members = enumeration.GetType().GetMembers();
foreach (MemberInfo member in members) {
results.Add(member.Name);
}

return results;
}

To bind to these results, you should simply need to write:

MyComboBox.DataSource = ConvertEnumForBinding(new CustomerType());

Easy huh? Unfortunately, it’s not quite that simple. ”

He goes into more details, fully answering Mr. Pietrek’s question at Paul Stovell’s personal Blog


 
Indelv.com is for sale!
 
ERP systemen
Alle ERP-systemen op een rij, compleet met ERP-nieuws en ERP-software informatie.
www.ERPcentraal.nl
ERP systemen
Alle ERP-systemen op een rij.
www.erpmatrix.nl

Indelv.com is for sale!

Quick Links
Our Friends
Cool Places
Visit also
About Us