Is it possible to define own comparer for columns in DataGrid

1 Answer 16 Views
DataGrid
Pavel Krebs
Top achievements
Rank 1
Pavel Krebs asked on 10 Dec 2024, 09:28 AM

Hello,

I have a RadDatagrid with more columns and I would like to use sorting functionality by clicking on column headers as it is implemented. Is it possible for some text columns to define own comparer. I need to compare strings "naturally" like: "Ring 1", "Ring 2", Ring 10", "Ring 11",...

Thank you,

 

Pavel

1 Answer, 1 is accepted

Sort by
0
Martin Ivanov
Telerik team
answered on 12 Dec 2024, 02:13 PM

Hello Pavel,

To achieve your requirement, you can implement a custom DataGrid column and override its CreateSortDescriptor method. This will allow you to set the Comparer property of the created SortDescriptorBase object.

 public class CustomDataGridTextColumn  : DataGridTextColumn
 {
     protected override SortDescriptorBase CreateSortDescriptor()
     {
         var descriptor = base.CreateSortDescriptor();
         descriptor.Comparer = new NaturalStringComparer();
         return descriptor;
     }
 }

 public class NaturalStringComparer : IComparer
 {
     [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
     public static extern int StrCmpLogicalW(string psz1, string psz2);

     public int Compare(object? a, object? b)
     {
         return StrCmpLogicalW((string)a, (string)b);
     }
 }

I also attached a sample project showing this idea. I hope it helps.

Regards,
Martin Ivanov
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
DataGrid
Asked by
Pavel Krebs
Top achievements
Rank 1
Answers by
Martin Ivanov
Telerik team
Share this question
or