Enum value `Browsable (false)`

there is a way to make the enumeration value inaccessible for viewing in the combo box
or just not to return with Enum.GetValues() ??

 public enum DomainTypes { [Browsable(true)] Client = 1, [Browsable(false)] SecretClient = 2, } 
+4
source share
3 answers

There is nothing already suitable for you with the Enum.GetValues() method. If you want to use attributes, you can create your own attribute and use it through reflection:

 public class BrowsableAttribute : Attribute { public bool IsBrowsable { get; protected set; } public BrowsableAttribute(bool isBrowsable) { this.IsBrowsable = isBrowsable; } } public enum DomainTypes { [Browsable(true)] Client = 1, [Browsable(false)] SecretClient = 2, } 

And then you can use reflection to check for custom attributes and generate an Enums list based on the Browsable attribute.

+1
source

This is a general method (based on another SO answer that I cannot find) that you can call for any enumeration. By the way, the Browsable attribute is already defined in System.ComponentModel. For instance:

 ComboBox.DataSource = EnumList.Of<DomainTypes>(); ... public class EnumList { public static List<T> Of<T>() { return Enum.GetValues(typeof(T)) .Cast<T>() .Where(x => { BrowsableAttribute attribute = typeof(T) .GetField(Enum.GetName(typeof(T), x)) .GetCustomAttributes(typeof(BrowsableAttribute),false) .FirstOrDefault() as BrowsableAttribute; return attribute == null || attribute.Browsable == true; } ) .ToList(); } } 
+5
source

It really is not possible to do this in C # - public enumeration provides to all members. Instead, consider using a wrapper class to hide / expose elements selectively. Maybe something like this:

 public sealed class EnumWrapper { private int _value; private string _name; private EnumWrapper(int value, string name) { _value = value; _name = name; } public override string ToString() { return _name; } // Allow visibility to only the items you want to public static EnumWrapper Client = new EnumWrapper(0, "Client"); public static EnumWrapper AnotherClient= new EnumWrapper(1, "AnotherClient"); // The internal keyword makes it only visible internally internal static readonly EnumWrapper SecretClient= new EnumWrapper(-1, "SecretClient"); } 

Hope this helps. Good luck

+1
source

All Articles