codecompleting
codecompleting

Reputation: 9621

Need to display a list of checkboxes based on an enumeration

I need to display a list of checkboxes, 3 per html table row.

The label and value of each checkbox will come from an enumeration.

What is the best way to construct this and display it in webforms?

I'm thinking of just using a literal control, and generating the the controls inside of an htmltable object.

Comments?

Upvotes: 3

Views: 288

Answers (1)

Tejs
Tejs

Reputation: 41256

I'd consider a decorator pattern with data.

 public enum MyEnum
 {
     [Description("Display Text")]
     SomeEnumValue = 1,

     [Description("More Display Text")]
     AnotherEnumValue = 2
 }

You would then make a method that gets that data like so:

public IEnumerable<ListItem> GetListItemsForEnum<EnumType>() where EnumType : struct
{
    if (!typeof(EnumType).IsEnum) throw new InvalidOperationException("Generic type argument is not a System.Enum");
    var names = Enum.GetNames(typeof(EnumType));

    foreach (var name in names)
    {
        var item = new ListItem();
        var fieldInfo = typeof(EnumType).GetField(name);
        var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault(x => x is DescriptionAttribute) as DescriptionAttribute;
        if (attribute != null)
        {
            item.Text = attribute.Description;
            item.Value = Enum.Parse(typeof(EnumType), name).ToString();
            yield return item;
        }
    }
}

Then you can simply call that method on any enum with the description attributes and get an IEnumerable<ListItem> to use when binding.

Upvotes: 4

Related Questions