Data bind enum properties to grid and display description

前端 未结 3 1352
挽巷
挽巷 2020-12-14 04:34

This is a similar question to How to bind a custom Enum description to a DataGrid, but in my case I have multiple properties.

public enum ExpectationResult
{         


        
3条回答
  •  悲哀的现实
    2020-12-14 05:01

    A TypeConverter will usually do the job; here's some code that works for DataGridView - just add in your code to read the descriptions (via reflection etc - I've just used a string prefix for now to show the custom code working).

    Note you would probably want to override ConvertFrom too. The converter can be specified at the type or the property level (in case you only want it to apply for some properties), and can also be applied at runtime if the enum isn't under your control.

    using System.ComponentModel;
    using System.Windows.Forms;
    [TypeConverter(typeof(ExpectationResultConverter))]
    public enum ExpectationResult
    {
        [Description("-")]
        NoExpectation,
    
        [Description("Passed")]
        Pass,
    
        [Description("FAILED")]
        Fail
    }
    
    class ExpectationResultConverter : EnumConverter
    {
        public ExpectationResultConverter()
            : base(
                typeof(ExpectationResult))
        { }
    
        public override object ConvertTo(ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture, object value,
            System.Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return "abc " + value.ToString(); // your code here
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
    
    public class TestResult
    {
        public string TestDescription { get; set; }
        public ExpectationResult RequiredExpectationResult { get; set; }
        public ExpectationResult NonRequiredExpectationResult { get; set; }
    
        static void Main()
        {
            BindingList list = new BindingList();
            DataGridView grid = new DataGridView();
            grid.DataSource = list;
            Form form = new Form();
            grid.Dock = DockStyle.Fill;
            form.Controls.Add(grid);
            Application.Run(form);
        }
    }
    

提交回复
热议问题