This is a migrated thread and some comments may be shown as answers.
Custom sort order for grid
22 Answers 404 Views
This is a migrated thread and some comments may be shown as answers.
stealthsid
Top achievements
Rank 1
stealthsid asked on 30 Jun 2008, 03:28 PM
I was able to create my own sort order for a radtreeview pretty easily by creating an IComparer class, but I appear to be locked in to Ascending/Descending/None for the GridView.

Is there any way (I'm fine with inheriting objects if necessary) to allow a custom sort order in a GridView? I also don't want to apply that sort order right away, I only want it to occur if the user chooses to sort the column in question.

22 Answers, 1 is accepted

Sort by
0
Jack
Telerik team
answered on 01 Jul 2008, 12:13 PM
Hi Sidney,

Thank you for your question.

Currently RadGridView doesn't support this kind of functionality. Nevertheless, I admit that custom sorting is a good feature and we will consider implementing it in a future release of RadControls.

Do not hesitate to contact me if you have other questions.

Kind regards,
Jack
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Guillaume Crétot Richert
Top achievements
Rank 1
answered on 28 Sep 2009, 07:21 PM
Any ETA on when custom sorting will be supported with RadGridView?

Thanks.
0
Julian Benkov
Telerik team
answered on 29 Sep 2009, 01:10 PM
Hello Guillaume Crétot Richert,

This functionality is supported in the current edition of RadGridView. You must download and use the last edition of RadControls for Winforms. To enable custom sorting for some column, you must set its CustomDataOperation property and handle RadGridView CustomSorting event.

this.radGridView.Columns["City"].CustomDataOperation = CustomDataOperation.Sorting; 
private void radGridView1_CustomSorting(object sender, GridViewCustomSortingEventArgs e) 
    if (e.Column.SortOrder == RadSortOrder.Ascending) 
    { 
        e.SortResult = ((IComparable)e.CellValue1).CompareTo(e.CellValue2); 
    } 
    else 
    { 
        e.SortResult = ((IComparable)e.CellValue1).CompareTo(e.CellValue2) * (-1); 
    } 

Do not hesitate to write me back if you have further questions.

Greetings,
Julian Benkov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Guillaume Crétot Richert
Top achievements
Rank 1
answered on 29 Sep 2009, 08:22 PM
Worked like a charm.

Thanks!
0
wima
Top achievements
Rank 1
answered on 15 Dec 2009, 06:24 AM
Hello

This code and also the sample from here http://www.telerik.com/support/kb/winforms/gridview/sorting-by-displaymember-on-combobox-lookup-column.aspx does not work. When I try to sort the column, I get an exception:

System.InvalidOperationException was unhandled
  Message="Fehler beim Vergleichen von zwei Elementen im Array."
  Source="mscorlib"
  StackTrace:
       bei System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
       bei System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
       bei System.Array.Sort[T](T[] array, IComparer`1 comparer)
       bei Telerik.WinControls.Data.DataAccessComponent.SortCustom(GridViewDataColumn column)
       bei Telerik.WinControls.Data.DataAccessComponent.UpdateIndex()
       bei Telerik.WinControls.Data.DataAccessComponent.Telerik.WinControls.Data.ExpressionHelper.IExpressionChangeNotificationConsumer.SortExpressionChanged()
       bei Telerik.WinControls.Data.ExpressionHelper.SortExpressionChanged(Object sender, NotifyCollectionChangedEventArgs e)
       bei Telerik.WinControls.Data.ExpressionFieldCollection`1.NotifyListenersCollectionChanged(NotifyCollectionChangedEventArgs e)
       bei Telerik.WinControls.Data.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
       bei Telerik.WinControls.UI.RadSortExpressionCollection.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
       bei Telerik.WinControls.Data.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedAction action, Object item, Int32 index)
       bei Telerik.WinControls.Data.ObservableCollection`1.InsertItem(Int32 index, T item, Action`1 approvedAction)
       bei Telerik.WinControls.Data.ObservableCollection`1.InsertItem(Int32 index, T item)
       bei Telerik.WinControls.Data.ItemObservableCollection`1.InsertItem(Int32 index, T item)
       bei Telerik.WinControls.UI.RadSortExpressionCollection.InsertSortField(Int32 index, GridSortField sortField)
       bei Telerik.WinControls.UI.RadSortExpressionCollection.TryInsertSortField(Int32 index, GridSortField sortField)
       bei Telerik.WinControls.UI.RadSortExpressionCollection.InsertItem(Int32 index, GridSortField item)
       bei System.Collections.ObjectModel.Collection`1.Add(T item)
       bei Telerik.WinControls.UI.GridViewDataColumn.AdvanceSortOrder(Boolean multipleColumnSortingMode)
       bei Telerik.WinControls.UI.GridHeaderCellElement.OnMouseUp(MouseEventArgs e)
       bei Telerik.WinControls.RadElement.OnCLREventsRise(RoutedEventArgs args)
       bei Telerik.WinControls.RadElement.OnBubbleEvent(RadElement sender, RoutedEventArgs args)
       bei Telerik.WinControls.RadItem.OnBubbleEvent(RadElement sender, RoutedEventArgs args)
       bei Telerik.WinControls.RadElement.RaiseBubbleEvent(RadElement sender, RoutedEventArgs args)
       bei Telerik.WinControls.RadItem.RaiseBubbleEvent(RadElement sender, RoutedEventArgs args)
       bei Telerik.WinControls.RadElement.RaiseRoutedEvent(RadElement sender, RoutedEventArgs args)
       bei Telerik.WinControls.RadElement.DoMouseUp(MouseEventArgs e)
       bei Telerik.WinControls.ComponentInputBehavior.OnMouseUp(MouseEventArgs e)
       bei Telerik.WinControls.RadControl.OnMouseUp(MouseEventArgs e)
       bei Telerik.WinControls.UI.RadGridView.OnMouseUp(MouseEventArgs e)
       bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       bei System.Windows.Forms.Control.WndProc(Message& m)
       bei System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       bei Telerik.WinControls.RadControl.WndProc(Message& m)
       bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       bei System.Windows.Forms.Application.Run(Form mainForm)
       bei ComboBoxSorting.Program.Main() in C:\Users\marco\Desktop\CustomSorting~\ComboBoxSorting\ComboBoxSorting\Program.cs:Zeile 17.
       bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       bei System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.ArgumentException
       Message="Spalte 'ProductID1' gehört nicht zu Tabelle GridDataTable."
       Source="System.Data"
       StackTrace:
            bei System.Data.DataRow.GetDataColumn(String columnName)
            bei System.Data.DataRow.get_Item(String columnName)
            bei Telerik.WinControls.UI.GridViewRowInfo.get_Item(String colName)
            bei Telerik.WinControls.UI.RowComparer.Compare(GridViewRowInfo x, GridViewRowInfo y)
            bei System.Collections.Generic.ArraySortHelper`1.SwapIfGreaterWithItems(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
            bei System.Collections.Generic.ArraySortHelper`1.QuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer)
            bei System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
       InnerException:


In our company we have the version 2009.1.9.316, but its the same with the newest trial dll's.
Can anyone help me? Thank you.
Marco Wittwer
0
Martin Vasilev
Telerik team
answered on 17 Dec 2009, 02:42 PM
Hi wima,

Thank you for writing. I have not managed to reproduce the described exception. Please, make sure that you are using the latest version of RadControls. If you still experience any difficulties with custom sorting, please open a new support ticket and send us a small sample project demonstrating your scenario. This will help us to investigate the issue further.

Greetings, Martin Vasilev
the Telerik team

 


Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
DGPunkt
Top achievements
Rank 1
answered on 06 Jan 2010, 12:27 PM
Hallo everybody,

as referred in wima´s post from Dec 15, 2009 I tried your example from knowledgebase:

Custom sorting by DisplayMember on ComboBox/Lookup column

Article relates to RadControls for WinForms Q3 2008 SP2
Created by Martin Vassilev
Last modified Feb. 19, 2008
Last modified by Martin Vassilev
 
And I got the same InvalidOperationException, wima had. We´re using RadControls for WinForms Q3SP1 2009.

All I wanted to do is sorting a ComboBoxColumn by DisplayValue...

Any suggestions?


Greetings,
Daniel

0
Martin Vasilev
Telerik team
answered on 11 Jan 2010, 05:09 PM
Hello DGPunkt,

Thank you for contacting us.

I managed to reproduce the described exception with the latest release Q3 2009 SP1. It is related to an issue with the columns' unique naming convention. We will address it in one of the next releases. Currently, you can work-around it if you set a different UniqueName for the ProductID column before adding the GridViewComboBoxColumn (regarding the example in the KB Article):
private void Form1_Load(object sender, EventArgs e)      
{
    this.radGridView1.Columns["productID"].UniqueName = "product"
       
    GridViewComboBoxColumn comboCol = new GridViewComboBoxColumn();      
       
    comboCol.DataSource = this.productsBindingSource; //this.nwindDataSet.Products;      
    comboCol.ValueMember = "ProductID";      
    comboCol.DisplayMember = "ProductName";      
    comboCol.FieldName = "ProductID";      
    comboCol.HeaderText = "Product Name";      
    comboCol.Width = 250;      
            
    this.radGridView1.Columns.Insert(2, comboCol);      
    comboCol.CustomDataOperation = CustomDataOperation.Sorting;      
}    

I have updated your Telerik points for reporting this issue. Do not hesitate to contact me again if you have any other questions.

Greetings,
Martin Vasilev
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
DGPunkt
Top achievements
Rank 1
answered on 21 Jan 2010, 05:09 PM
Hello Martin,
hello telerik-Team,

your solution works for that problem, but there might be another problem:

The same error occurs if the unique name of the combobox column is different than the datasources field name like:

GridViewComboBoxColumn column = new GridViewComboBoxColumn("ColumnName", "DatasourceFieldName");

Greetings,
Daniel

 

 

 

 

0
Martin Vasilev
Telerik team
answered on 26 Jan 2010, 05:16 PM
Hello Daniel,

Thank you for getting back to me.

You are correct, it throws the same exception and the underlying reason is the same. I have already logged the issue in our issue tracking system. Thank you once again for your participation. Let me know if you have any other questions.

Sincerely yours,
Martin Vasilev
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Mike
Top achievements
Rank 1
answered on 02 Mar 2011, 08:15 PM
It's been over a year now.  Has the problem of not being able to sort by the DisplayMember of a ComboBox column been resolved?
0
Martin Vasilev
Telerik team
answered on 08 Mar 2011, 11:05 AM
Hi wima,

Thank you for the questions.

In the latest version sorting by DisplayMember for combo-box column is implemented by default and there is no need to use the custom sorting to include this functionality.

Let me know if you have any additional questions.

Best wishes,
Martin Vasilev
the Telerik team
Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
0
David Storey
Top achievements
Rank 1
answered on 12 Apr 2011, 12:49 PM
The sort order does not work on "DisplayMember" as expected for a GridViewComboBoxColumn.

If the datasource associated with the column is sorted alphabetically and the id associated with this is also in the same order then the "DisplayMember" sorting works correctly.  See attached code.  I think this is a bug, as most lists will never be ordered like this.

So a datasource for the GridViewComboBoxColumn would sort correctly if it was like this

list.Add(new ComboItem(0, "A Test"));
list.Add(new ComboItem(1, "B Test"));
list.Add(new ComboItem(2, "C Test"));
list.Add(new ComboItem(3, "D Test"));

but would fail (revert to ValueMember sorting) if it was like this

list.Add(new ComboItem(0, "C Test"));
list.Add(new ComboItem(1, "A Test"));
list.Add(new ComboItem(2, "D Test"));
list.Add(new ComboItem(3, "B Test"));

Can you confirm this is a bug?  Im assuming the best workaround would be to use CustomSorting?

Im using Telerik.WinControls.GridView version 2011.1.11.315

Thanks
Dave
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Telerik.WinControls.UI;
 
namespace GridViewSorting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            var list = new List<ComboItem>();
 
            if (MessageBox.Show("Test Alpha list ordered?", "Order", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //sorting works on DisplayMember
                list.Add(new ComboItem(0, "A Test"));
                list.Add(new ComboItem(1, "B Test"));
                list.Add(new ComboItem(2, "C Test"));
                list.Add(new ComboItem(3, "D Test"));
            }
            else
            {
                //sorting works on ValueMember
                list.Add(new ComboItem(0, "C Test"));
                list.Add(new ComboItem(1, "A Test"));
                list.Add(new ComboItem(2, "D Test"));
                list.Add(new ComboItem(3, "B Test"));
            }
            radGridView1.MasterTemplate.Columns.Add("Test1", "TestId", "Test");
            radGridView1.MasterTemplate.Columns.Add(new GridViewComboBoxColumn("Test")
                                                        {
                                                            Width = 150,
                                                            HeaderText = "Sort",
                                                            FieldName = "Test",
                                                            DataSource = list,
                                                            DisplayMember = "Description",
                                                            ValueMember = "Key",
                                                            MinWidth = 100
                                                        });
 
            LoadGrid();
        }
 
        private void LoadGrid()
        {
            var data = new List<DataItem>();
 
            var rnd = new Random(0);
 
            for (var i = 1; i < 30; i++)
                data.Add(new DataItem(rnd.Next(0, 3)));
            radGridView1.MasterTemplate.DataSource = data;
 
        }
    }
 
    public class DataItem
    {
        public DataItem(int test)
        {
            Test = test;       
        }
        public int Test { get; set; }
    }
 
 
    public class ComboItem
    {
        public ComboItem(int key, string description)
        {
            Key = key;
            Description = description;
        }
        public int Key { get; set; }
        public string Description { get; set; }
    }
}
0
Martin Vasilev
Telerik team
answered on 15 Apr 2011, 11:56 AM
Hello David Storey,

Thank you for your sample code.

I confirm that actually we still are sorting by ValueMember as default behaviour in our combo-box column. We will consider to add an API for easy switching to sort based on DisplayMember in one of the next releases. I am adding this as feature request and you can track it here.

In order to implement your requirement with current version, you can use custom sorting. Please consider the following code:
void radGridView1_CustomSorting(object sender, GridViewCustomSortingEventArgs e)
{
    foreach (var descriptor in e.Template.SortDescriptors)
    {
        if (descriptor.PropertyName == "Test")
        {
            object value1 = ((GridViewComboBoxColumn)e.Template.Columns["Test"]).GetLookupValue(e.Row1.Cells["Test"].Value);
            object value2 = ((GridViewComboBoxColumn)e.Template.Columns["Test"]).GetLookupValue(e.Row2.Cells["Test"].Value);
 
            e.SortResult = String.Compare(value1.ToString(), value2.ToString());
            return;
        }
    }
    e.Handled = false;
}

Hope this helps. Let me know if you have any additional questions.

Regards,
Martin Vasilev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
David Storey
Top achievements
Rank 1
answered on 20 Apr 2011, 04:02 PM
Thanks Martin,

Just for completeness I needed to make a small modification

e.SortResult = e.Template.Columns["Test"].SortOrder == RadSortOrder.Descending ?  value2.CompareTo(value1) : value1.CompareTo(value2);
0
Theo
Top achievements
Rank 2
answered on 17 Apr 2012, 09:38 AM
Hey there. 
Here's a snippet that does it in VB and also a bit more generic.
Private Sub dgvMasterDividends_CustomSorting(sender As System.Object, e As Telerik.WinControls.UI.GridViewCustomSortingEventArgs) Handles dgvMasterDividends.CustomSorting
    For Each sd As SortDescriptor In e.Template.SortDescriptors
        If TypeOf e.Template.Columns(sd.PropertyName) Is GridViewMultiComboBoxColumn Then
            Dim val1 = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row1.Cells(sd.PropertyName).Value)
            Dim val2 = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row2.Cells(sd.PropertyName).Value)
 
            e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
        Else
            Try
                Dim val1 = e.Row1.Cells(sd.PropertyName).Value
                Dim val2 = e.Row2.Cells(sd.PropertyName).Value
 
                e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
            Catch ex As Exception
                e.Handled = False
                Return
            End Try
        End If
    Next
    e.Handled = True
End Sub

We use GridViewMultiComboBoxColumn on our grids, but I don't see why you would not be able to cast the column to additional / other column types and handle each type independently.
Note that this only works for single column ordering. I have not been able to get the 'SHIFT+click' to get multiple column sorting working.
Hope this helps.
Theo
0
Julian Benkov
Telerik team
answered on 20 Apr 2012, 09:25 AM
Hello Theo,

To handle this behavior you must break the loop when the result is not equal to zero. Here is the modified code snippet:
Private Sub dgvMasterDividends_CustomSorting(sender As System.Object, e As Telerik.WinControls.UI.GridViewCustomSortingEventArgs)
    For Each sd As SortDescriptor In e.Template.SortDescriptors
        If TypeOf e.Template.Columns(sd.PropertyName) Is GridViewMultiComboBoxColumn Then
            Dim val1 As dynamic = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row1.Cells(sd.PropertyName).Value)
            Dim val2 As dynamic = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row2.Cells(sd.PropertyName).Value)
 
            e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
        Else
            Try
                Dim val1 As dynamic = e.Row1.Cells(sd.PropertyName).Value
                Dim val2 As dynamic = e.Row2.Cells(sd.PropertyName).Value
 
                e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
                If e.SortResult <> 0 Then
                    Exit Try
                End If
            Catch ex As Exception
                e.Handled = False
                Return
            End Try
        End If
    Next
    e.Handled = True
End Sub

I hope this helps.

Kind regards,
Julian Benkov
the Telerik team
RadControls for WinForms Q1'12 release is now live! Check out what's new or download a free trial >>
0
Theo
Top achievements
Rank 2
answered on 21 Apr 2012, 08:22 AM
Hi there
Should it not be Exit For, why do you exit the try.
If e.SortResult <> 0 means that there was a difference so it needs to be sorted (-1 = smaller, 0 = equal, +1 = bigger) or is this to handle the multi-column sorting (you just refer to handle 'this' behavior in your post so it is a bot confusing.
What does "If e.SortResult <> 0 then Exit Try" actually achieve?

Secondly, in which namespace or reference does the 'dynamic' datatype reside? I cannot define val1 and val2 as dynamic. JustCode says that it wants to generate a stub or new datatype?

Thank you
Theo Jacobs


0
Julian Benkov
Telerik team
answered on 23 Apr 2012, 03:21 PM
Hello Theo,

Sorry for the introduced inconvenience. I used a code converter to convert my example to VB, thus it produced the wrong code. Here is a example using a native VB project: 
Private Sub GridViewCustomSorting(sender As Object, e As GridViewCustomSortingEventArgs)
 
    For Each sd As SortDescriptor In e.Template.SortDescriptors
        If TypeOf e.Template.Columns(sd.PropertyName) Is GridViewMultiComboBoxColumn Then
            Dim val1 As Object = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row1.Cells(sd.PropertyName).Value)
            Dim val2 As Object = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row2.Cells(sd.PropertyName).Value)
 
            e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
        Else
            Try
                Dim val1 As Object = e.Row1.Cells(sd.PropertyName).Value
                Dim val2 As Object = e.Row2.Cells(sd.PropertyName).Value
 
                e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
                If e.SortResult <> 0 Then
                    Exit For
                End If
            Catch ex As Exception
                e.Handled = False
                Return
            End Try
        End If
    Next
 
    e.Handled = True
End Sub

In the example the Exit operator is used to stop the next loop when the SortResult is different from 0, in other words when the two rows are different for the values currently compared, the additional compare of values is not needed to the order rows in the collection. When the values are equal, the next SortDescriptor value is processed to determine the order of the rows. The used algorithm is applied when we have more than one SortDescriptor in the SortDescriptors collection. When the user select more columns for sorting using 'SHIFT+click' then multiple columns are added to SortDescriptors collection.

I hope this helps. 
 
Greetings,
Julian Benkov
the Telerik team
RadControls for WinForms Q1'12 release is now live! Check out what's new or download a free trial >>
0
Theo
Top achievements
Rank 2
answered on 23 Apr 2012, 04:20 PM
Hi there
Thank you for the clarification. Thought the exit try looked suspicious.

I understand the reason why for each is used, but a) if you exit for then the loop does not continue for next descriptor, should it not be instead of exit for rather Continue so that next item in loop can be used? and b) I tested the solution (basically it's just the exit for that was added) and I can still not get it working so that multiple columns are sorted in the order that you clicked on the column headers.

If you refer to the attachments. 
1. Click Instrument        - Clicked on Instruments column, correctly sorted
2. Shift+Click Portfolio  - pressed and held shift down, clicked on portfolio, now grid sorted only according to portfolio, Instrument still has sort header image although sorting not on that column occurs anymore
3. Shift+Click Event Type - Same thing happens, now only sorted on EventType, other 2 columns not sorted

Expected behavior is that grid would have been sorted by instrument, then further by portfolio and then further by EventType

Am I missing something?
Thank you
Theo
0
Julian Benkov
Telerik team
answered on 26 Apr 2012, 03:04 PM
Hello Theo,

I have reviewed the code snippet again and I found that the loop break does not work for the ComboBox columns, so I extended the code snippet to include this functionality:
Private Sub GridViewCustomSorting(sender As Object, e As GridViewCustomSortingEventArgs)
 
    For Each sd As SortDescriptor In e.Template.SortDescriptors
        If TypeOf e.Template.Columns(sd.PropertyName) Is GridViewMultiComboBoxColumn Then
            Dim val1 As Object = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row1.Cells(sd.PropertyName).Value)
            Dim val2 As Object = DirectCast(e.Template.Columns(sd.PropertyName), GridViewMultiComboBoxColumn).GetLookupValue(e.Row2.Cells(sd.PropertyName).Value)
 
            e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
            If e.SortResult <> 0 Then
                Exit For
            End If
        Else
            Try
                Dim val1 As Object = e.Row1.Cells(sd.PropertyName).Value
                Dim val2 As Object = e.Row2.Cells(sd.PropertyName).Value
 
                e.SortResult = If(e.Template.Columns(sd.PropertyName).SortOrder = RadSortOrder.Descending, val2.CompareTo(val1), val1.CompareTo(val2))
                If e.SortResult <> 0 Then
                    Exit For
                End If
            Catch ex As Exception
                e.Handled = False
                Return
            End Try
        End If
    Next
 
    e.Handled = True
End Sub

When the two rows are not equal for the current sorting criteria, the next comparison to determine the rows position and the SortResult is not needed.

I you continue to experience the issues, please send me part of your data and the setup schema of your RadGridView columns, so I can investigate the issues locally and find best solution for your scenario. In order to be able to attach these, you will need to open a support ticket.

All the best,
Julian Benkov
the Telerik team
RadControls for WinForms Q1'12 release is now live! Check out what's new or download a free trial >>
0
Theo
Top achievements
Rank 2
answered on 30 Apr 2012, 09:31 AM
Thank you Julian, this seems to have done the job.
Asked by
stealthsid
Top achievements
Rank 1
Answers by
Jack
Telerik team
Guillaume Crétot Richert
Top achievements
Rank 1
Julian Benkov
Telerik team
wima
Top achievements
Rank 1
Martin Vasilev
Telerik team
DGPunkt
Top achievements
Rank 1
Mike
Top achievements
Rank 1
David Storey
Top achievements
Rank 1
Theo
Top achievements
Rank 2
Share this question
or