Friday, February 7, 2014

DevExpress MVC: Add an enum to a ComboBox

Here is a nice extension method I did to add an enum (text and values) to a DevExpress MVC ComboBox. it might also work with other kinds of widgets.

public static void AddEnum<TEnum>(this ListEditItemCollection instance)
 where TEnum : struct
{
 foreach (TEnum tos in (TEnum[])Enum.GetValues(typeof(TEnum)))
 {
  instance.Add(Enum.GetName(typeof(TEnum), tos), Convert.ToInt32(tos));
 }
}

Then I can do this:

Html.DevExpress().ComboBoxFor(model => model.OrderStatus,
 cbSettings =>
 {
  cbSettings.Properties.Items.AddEnum<Tag.TagOrderStatus>();
 }
).GetHtml();

the "struct" type constraint limits the type that can be used as the generic type, but won't limit it to only enums. Sh*t will hit the fan if something else that an enum is used, but it's a bit too complicated to apply a real functional compile time limit.

Have fun!

No comments: