Question

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?

Était-ce utile?

La 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.

Autres conseils

Why don't you incapsulate this logic in your data model?

like this

 class SomeDataModel : DataModelBase {

      public SomeEntityType Entity { get; private set; }

      public float Distance {
           get {
                return MetrixConvertionHelper.ConvertAccordingToSistemSettings(this.Entity.DistanceInFeets);
           }
           set {
                this.Entity.DistanceInFeets = MetrixConvertionHelper.ConvertDistanceBack(value);
           }
      }

 }

where MetrixConvertionHelper.ConvertAccordingToSistemSettings(float) - is your helper convertion function, SomeDataModel - is data model class, DistanceInFeets - original property of your entity type, wrapped by the data model, and MetrixConvertionHelper.ConvertDistanceBack(float) - is an oposite helper method, which converts current units to feets

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top