Martin
Martin

Reputation: 11041

GridView - Sorting Enum in Alphabetical Order

When sorting on a column in the GridView bound to an Enum, it sorts by the order of the Enum. I need it to sort by the string representation of the Enum. Here are the options I have seen, of which I like none of them.

  1. Reorder the Enum in alphabetical order - Bad because now the presentation is relying on the Business and Data Access Layer to "pre-sort" the data.
  2. Create a new object (datatable, new list, whatever) with myEnum.ToString() and bind this to the GridView - This one is not bad, but I would rather not.
  3. In my search, check to see if the column sorted is an Enum, then sort by the string representation of the column - Do I have to say why this is bad?

Number 2 would be my favorite so far, but like I said, I don't like it.

More info just in case - I am binding a List of IWhatever to the grid, and 2 columns are enums that need to be sorted by strings. There are also guid-type, string, and decimal columns in the grid that need to be sorted.

Upvotes: 1

Views: 1989

Answers (1)

Arthur
Arthur

Reputation: 8129

Try to use ViewModels. Basically you create ViewModel Objects that contains your Model Object (your IWhatever). This ViewModel exposes then new Properties and Methods which are used in your View. In Your case you would expose a property with the string representation of your Enum. The advantage is, that you could do any transformation logic you want.

See MVVM Pattern. http://en.wikipedia.org/wiki/Model_View_ViewModel

EDIT: Little Example:

public class WhateverViewModel
{
    public WhateverViewModel(IWhatever model)
    {
        this.model = model;
    }
    ...
    public string MyEnumView
    {
        get
        {
            return model.MyEnum.ToString(); 
        }
    }
    public string MyEnumView2
    {
        get
        {
            switch(model.MyEnum)
            {
                case MyEnumType.A: return "Hello";
                case MyEnumType.B: return "World";
            } 
        }
    }
}

Upvotes: 2

Related Questions