Introduction
This article presents a small (3) collection of classes that allow
enum
s to
be used as data sources to a combobox, listbox etc. The classes use reflection at
runtime to generate a list of values that the combobox or listbox uses to full
its items collection.
Background
I was developing an application data model and started modelling object
states as enum
s. When I came to developing the forms create or update these
items I wanted those same enum
values to be available for user selection. Not
wanting to retype the the enum
values I thought using reflection might be a cool
way of solving the problem. Two options came to mind, derive from the control
classes to allow enum
types to be used as a
DataSource
or implement a collection
class to supply the values. I chose the second because I thought a collection of
enum
name/value pairs would be more useful.
Using the code
Using the code is straightforward. After defining your enumeration type and
control, instantiate a an instance of the EnumItemCollection
class passing the type of your
enum
as parameter.
The simply assign this object to the controls DataSouce
property
public class EnumDatasourceForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ComboBox colourCombo;
private System.Windows.Forms.ListBox colourListBox;
private System.Windows.Forms.CheckedListBox colourCheckedListBox;
private System.Windows.Forms.Button button1;
private AgileThought.Data.EnumItemCollection coloursCollection =
new AgileThought.Data.EnumItemCollection(typeof(Colours));
...
private void EnumDatasourceForm_Load(object sender, System.EventArgs e)
{
colourCombo.DataSource = coloursCollection;
colourListBox.DataSource = coloursCollection;
colourCheckedListBox.DataSource = coloursCollection;
}
private void colourCombo_SelectedIndexChanged(object sender, System.EventArgs e)
{
EnumPair selectedItem = (EnumPair)colourCombo.SelectedValue;
MessageBox.Show(this, "You choose " +
selectedItem.Name + " " + selectedItem.Value);
}
...
}
The EnumPair
class contains the enum
name and value it can be retrieved from
the SelectedValue
property of the control.
History
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.