The following is a helper class which you can use to pass a combo box or list box and an enum for data binding.
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace EnumTools
{
public enum TRANSPORT : uint
{
Car = 1,
Bus = 2,
HandsomeCab = 3,
Train = 4,
Aeroplane = 5
}
public class BindableObject
{
private string m_strValue = "";
private string m_strText = "";
public BindableObject(string strValue, string strText)
{
m_strValue = strValue;
m_strText = strText;
}
public string Value
{
get
{
return m_strValue;
}
}
public string Text
{
get
{
return m_strText;
}
}
}
public class EnumBinder
{
public static void DataBind(ListControl objListControl, Type objEnumType)
{
Regex objRegEx = new Regex(@"[A-Z][a-z]*", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
//
// get the values from the enumeration
//
Array objValues = Enum.GetValues(objEnumType);
ArrayList objBindObjects = new ArrayList();
MatchCollection objMatches = null;
string strValueName = "", strDisplayName = "";
//
// loop through each value
//
foreach(uint nValue in objValues)
{
strDisplayName = "";
//
// get the 'nice' name for the value
//
strValueName = Enum.GetName(objEnumType, nValue);
//
// split the nice name on camel casing
//
objMatches = objRegEx.Matches(strValueName);
//
// build up the display string
//
foreach(Match objMatch in objMatches)
{
strDisplayName += objMatch.Value + " ";
}
//
// add the current enum details as a bindable object
//
objBindObjects.Add(new BindableObject(nValue.ToString(), strDisplayName.Trim()));
}
//
// bind up
//
objListControl.DataSource = null;
objListControl.DisplayMember = "Text";
objListControl.ValueMember = "Value";
objListControl.DataSource = objBindObjects;
}
}
}
The TRANSPORT enum is only included in the above class for this example.
To then use this class to bind the example TRANSPORT enum to a combo box, do the following:
EnumTools.EnumBinder.DataBind(comboBox1, typeof(EnumTools.TRANSPORT));
You may pass a list box in place of the combo box variable above if that is your UI control of choice.
|