How to display enum values in datagridview column

后端 未结 5 1023
臣服心动
臣服心动 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:29

    You can use the CellTemplate property of the respective column. So first create a class for the cell template, overriding GetFormattedValue

    public class VATGridViewTextBoxCell : DataGridViewTextBoxCell
    {
        protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
        {
            Price.VATRateEnum r = (Price.VATRateEnum)(int)value;
            switch (r)
            {
                case Price.VATRateEnum.None: return "0%";
                case Price.VATRateEnum.Low: return "14%";
                case Price.VATRateEnum.Standard: return "20%";
                default:
                    throw new NotImplementedException()
            }
        }
    }
    

    then assign new instances of it to the columns' cell templates. Note that the change does not take effect until you refresh the grid and that's why I put it into the constructor:

    public frmGoods()
    {
        InitializeComponent();
        this.sellingVATDataGridViewTextBoxColumn.CellTemplate = new VATGridViewTextBoxCell();
        this.buyingVATDataGridViewTextBoxColumn.CellTemplate = new VATGridViewTextBoxCell();
    }
    

提交回复
热议问题