Search code examples
.netdatagridviewcell-formatting

How do I implement DataGridView column that can display in different units?


I have a DataGridView (.NET winforms) bound to a collection. One of the fields is a distance stored in feet. But, the grid needs to be able to display in feet or meters (but always store as feet) depending on a system setting. How do I do this? It feels as if I need to use the CellParsing event to convert the value to feet (if display setting is meters) on user entry. And, I also need to use the CellFormatting event to convert the displayed value to meters if the display setting is set to meters. Does that sound right or is there a simpler way?


Solution

  • The simplest way would e to add a property that applies the calculation:

    [DisplayName("Distance (feet)")]
    public decimal DistanceFeet {get;set;}
    [DisplayName("Distance (metres)")]
    public decimal DistanceMetres {
        get { return FeetToMetres(DistanceFeet); }
        set { DistanceFeet = MetresToFeet(value); }
    }
    

    Personally, I also use metres a the primary unit, but that is just me ;)

    Now just databind to either, or show/hide the columns, as you find convenient.