How to: Show Values of Enumeration in CheckedComboBoxEdit
- 3 minutes to read
The following example shows how to edit bit fields (a set of flags) in a CheckedComboBoxEdit control.
The control displays values of a custom MyColors enum, which has five simple flags (None through Yellow) and one combined flag (Green). Combined flags are not supported by the CheckedComboBoxEdit control. Items that correspond to these flags must be manually removed from the RepositoryItemCheckedComboBoxEdit.Items collection (see the removeCombinedFlags method which performs this operation).
The RepositoryItemCheckedComboBoxEdit.SetFlags method populates the RepositoryItemCheckedComboBoxEdit.Items collection with items corresponding to all available flags (except for a flag with a zero value). Then, the removeCombinedFlags method is called to remove items corresponding to combined flags. Finally, the editor’s initial value is specified using the CheckedComboBoxEdit.SetEditValue method.
The following image shows the result:
Note that the Green flag is not present in the dropdown list, although you can set this flag to the control’s value.
using DevExpress.XtraEditors.Repository;
[Flags]
enum MyColors {
None = 0x00,
Black = 0x01,
White = 0x02,
Blue = 0x04,
Yellow = 0x08,
Green = Blue | Yellow
}
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
// Populate the Items collection with all available flags.
checkedComboBoxEdit1.Properties.SetFlags(typeof(MyColors));
// Remove items that correspond to compound flags.
removeCombinedFlags(checkedComboBoxEdit1.Properties);
// Set an initial value.
checkedComboBoxEdit1.SetEditValue(MyColors.Black | MyColors.Green);
}
// Traverse through items and remove those that correspond to bitwise combinations of simple flags.
private void removeCombinedFlags(RepositoryItemCheckedComboBoxEdit ri) {
for (int i = ri.Items.Count - 1; i > 0; i--) {
Enum val1 = ri.Items[i].Value as Enum;
for (int j = i - 1; j >= 0; j--) {
Enum val2 = ri.Items[j].Value as Enum;
if (val1.HasFlag(val2)) {
ri.Items.RemoveAt(i);
break;
}
}
}
}
}