5

I would like to add custom property that offers a list of choices.

It is possible to use Enum type. The property will be then rendered as a combobox.

public enum Group
    {
        GroupA,
        GroupB,
        GroupC
    }

[WebBrowsable(true), 
Category("Miscellaneous"), 
Personalizable(PersonalizationScope.Shared),
WebDisplayName("Group name")]
public Group SelectedGroup
{
get { return _group;  }
set { _group = value;}
}

It works fine - but I would like to use more complex group names like "John Doe's group". Is there any way to do that? I haven't found anything and I'd prefer not to create EditorPart and do all those things manually.

1

1 Answer 1

3

Enums in .Net can have spaces with System.ComponentModel.DescriptionAttribute. Your example could be rewritten like this:

public enum Group
{
    [Description("John Doe's Group")]
    GroupA,
    [Description("Frank Star's Group")]
    GroupB,
    [Description("Stella Reinolds Group")]
    GroupC
}

Then using reflection you could access Description property

public static string GetGroupEnumDescription(Enum value)
{
    FieldInfo group= value.GetType().GetField(value.ToString());

    DescriptionAttribute[] descAttr= (DescriptionAttribute[])group.GetCustomAttributes(typeof(descAttr), false);

    if (descAttr!= null && descAttr.Length > 0) {
        return descAttr[0].Description;
    }
    else {
        return value.ToString();
    }
}

Then you will use this method GetGroupEnumDescription(Group.GroupA);

Putting this all together to populate your DropDownList you could use

foreach (Group group in Enum.GetValues(typeof(Group)))
{
    groupDropDown.Items.Add(GetGroupEnumDescription(group));
}
3
  • Thanks for your answer. But then I would have to create Editor Part and render dropdown manually, right? I'm wondering if its possible to do this that way by simply adding the property to webpart. Enums are rendered as a dropdown, but this dropdown is populated by enum's values' names - I haven't found any "Display Name". It doesn't support Description Attribute as well. Well, maybe the only solution is to make an Editor Part and populate the dropdown manually like you said...
    – movax
    Commented Sep 20, 2013 at 7:47
  • I think that the easiest way to achieve this is to create a webpart with a dropdownlist and in the editor part select the Enum to be populated. Each Enum will have its own values. And I made a proof of concept and it works Commented Sep 20, 2013 at 8:40
  • Okay, thanks. It's a pity that there is no such a functionality out of the box...
    – movax
    Commented Sep 20, 2013 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.