How to display enum values in datagridview column

后端 未结 5 983
臣服心动
臣服心动 2021-01-18 02:30

I have this Database, not of my design but I have to work with it, that contains a table like so :

 id  |   Name     |  status  | ...
-----+------------+-------         


        
5条回答
  •  迷失自我
    2021-01-18 03:07

    Currently, I don't quite understand what you mean by 1k items.

    But, all you have to do is create the enum for yourself like:

    public enum States
    {
         Invalid = 0,
         [Description("In developement")]
         Dev,
         Activ,
         Old,
         ...
    }
    

    And in your your formatting event you call this function

    /// 
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// 
    /// The Enum value for which the description is needed.
    /// If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
    
        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])
         fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
        if (attributes != null && attributes.Length > 0)
        {
            description = attributes[0].Description;
        }
    
        return description;
    }
    

    that way

    e.Value = Enum.GetName(typeof(States), e.Value).Description;
    

    All you have to do is check that you have defined all the enum values that are possible, and that you're operating on the correct column.

    If you have 1000 values in your status column, there is nothing that can help you to automate this in .Net. But it's a job that has to be done once, so it's not that hard.

提交回复
热议问题