2

Is there simpler way to correctly sort numeric data in a datagrid?

Explanation - When you click on a column header with data 1,5,10,2 it sorts it as text (1,10,2,5).

I have read that you can implement ICollectionView, to create your own custom sorting. Before I go down that path, I want to make sure there isn't an easier way.

2 Answers 2

3

A co-worker solved my problem. By wrapping the source object in a wrapper, you can then define a SortBLANK, which just returns the data as int instead of string. I then use SortMemberPath to set the sorting for that call. Note, this only works for the problem of numeric only sorting.

XAML(Partial):

<sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Header="MAC" FontSize="12"  Binding="{Binding macaddr}" Width="100"/>
    <sdk:DataGridTextColumn Header="Upload Rate" SortMemberPath="SortUpload"  FontSize="12"  Binding="{Binding uploadRate}" Width="3*"/>
    <sdk:DataGridTextColumn Header="Download Rate" SortMemberPath="SortDownload" FontSize="12"  Binding="{Binding downloadRate}" Width="3*"/>
</sdk:DataGrid.Columns>

Code-Behind(Partial):

public class OnlineDevicesWrapper
    {
        public string macaddr{get;set;}
        public string uploadRate { get; set; }
        public string downloadRate { get; set; }

        public int SortUpload
        {
            get
            {
                return int.Parse(uploadRate);
            }
        }

        public int SortDownload
        {
            get
            {
                return int.Parse(downloadRate);
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2

What you want is a natural string sort comparer, using the IComparer interface. There are several C# solutions out there, I've listed a few. Note that I don't think any of them are geared towards Silverlight specifically, though you shouldn't have too much trouble using them in Silverlight.

How to achieve Natural(human alpha-numeric ) Sorting, for silverlight datagrids using ViewModel?

http://www.codeproject.com/KB/string/NaturalSortComparer.aspx

Natural Sort Order in C#

http://www.codeproject.com/KB/recipes/csnsort.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.