Thursday, January 15, 2009

Binding Enum to ComboBox

Hi,

Whether it’s Windows Forms or Windows Presentation Foundation While working with ComboBox, we usually want to bind any list as ComboBox Items.

For example,

//In windows forms
string[] names = { "Microsoft", "IBM", "Apple" };
cmbNames.DataSource = names;  //cmbNames is comboBox ID

or

//In windows presentation foundation
string[] names = { "Microsoft", "IBM", "Apple"};
cmbNames.ItemsSource = names;  //cmbNames is comboBox ID

That’s simple! But today I wanted to convert enum constants into an array of string and I wanted to make it ItemsSource of combo. So I created an enum type “Names” and tried that

public enum Names

    Microsoft, 
    IBM, 
    Apple
}

Names nameList;
cmbNames.ItemsSource = nameList ; //compile time error-

A compile time error is raised claiming that Cannot implicitly convert type ‘Names’ to ‘System.Collections.IEnumerable’. So i searched for that and find a good single line solution :)

//For WPF
cmbNames.ItemsSource = Enum.GetNames(typeof(Names));

//and In windows forms
cmbNames.DataSource = Enum.GetNames(typeof(Names));

It will convert enum contants into string[]. To convert back from string to constant you can use Enum.Parse(…).

Nice Feature! Isn’t it?

1 comments:

Zain said...

nice nice... really handy...

Post a Comment