65.9K
CodeProject is changing. Read more.
Home

Enums as a DataSource

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.17/5 (8 votes)

Jul 26, 2004

1 min read

viewsIcon

65014

downloadIcon

1283

How to use an enum as a datasource for lists in .NET applications

Introduction

This article presents a small (3) collection of classes that allow enums 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 enums. 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

//
// Extract from code sample
//
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

  • 23/7/2004 First release