We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Sort SfDataGrid custom type column

Hello,

I have an SfDataGrid where several columns are of custom type (ie., a class) with the relevant settings here.

AllowSorting = true
AutoGenerateColumns = true
AutoGenerateColumnsForCustomType = true
AutoGenerateColumnsMode = Reset
AutoGenerateColumnsModeForCustomType = Parent

The grid displays correctly for the custom types (because I override the ToString() method). However, I also want to be able to click the column header and sort those columns. Therefore, I have implemented the IComparable interface and overridden CompareTo, for example like the code below.

        public int CompareTo(object other)
        {
            if (other is Advertiser)
                return this.AdvertiserName.CompareTo((other as Advertiser).AdvertiserName);
            return 1;
        }

However, after this, when I click on the Advertiser column above, nothing happens. My CompareTo method is not called. When I click on other columns with simple data type (int, string etc.), the sorting happens correctly.

I must have missed some settings somewhere. If you could let me know what else I should do, I'd appreciate it.

Thank you in advance.


6 Replies 1 reply marked as answer

VS Vijayarasan Sivanandham Syncfusion Team December 21, 2022 01:26 PM UTC

Hi Dinh,

We are able to understand your scenario. We are in need of some information related to the reported scenario.

Please provide more information related to your query.

  1. Confirm whether you are binding the DataSource as DataTable or ObservableCollection in SfDataGrid
  2. Code Snippet related to underlying model type (ex: custom type)
  3. Code Snippet related to custom comparer

Kindly revert to us with the above requested details. It will be more helpful for us to check the possibilities for resolving the reported problem.

Regard,

Vijayarasan S



DI Dinh replied to Vijayarasan Sivanandham December 22, 2022 02:33 AM UTC

Hi  Vijayarasan,

I'll simplify my code to a conceptual level as below.

    public class Campaign

    {
        public int CampaignID { get; set; }
        public string CampaignName { get; set; }
        public long Impressions { get; set; }
        public long AdSpend { get; set; }
        public Advertiser Advertiser { get; set; }
        public Brand Brand { get; set; }
    }
    public class Advertiser : IComparable
    {
        public int AdvertiserID { get; set; }
        public string AdvertiserName { get; set; }
        public int CompareTo(object other)
        {
            if (other is Advertiser)
                return this.AdvertiserName.CompareTo((other as Advertiser).AdvertiserName);
            return 1;
        }
        public override string ToString()
        {
            return AdvertiserName;
        }
    }
    public class Brand : IComparable
    {
        public int BrandID { get; set; }
        public string BrandName { get; set; }
        public int CompareTo(object other)
        {
            if (other is Brand)
                return this.BrandName.CompareTo((other as Brand).BrandName);
            return 1;
        }
        public override string ToString()
        {
            return BrandName;
        }
    }

Then in my GUI form, I populate sfDataGrid as below.

sfDataGrid.DataSource = dbContext.Campaign.ToList();

Where dbContext is EntityFramework 6 DatabaseContext (so I guess it's an ObservableCollection). SfDataGrid is able to display all 6 columns correctly. Of those, columns CampaignID, CampaignName, Impressions, AdSpend sort correctly while Advertiser and Brand do not (nothing happens when I click on them).



VS Vijayarasan Sivanandham Syncfusion Team December 22, 2022 07:19 PM UTC

Dinh,


We are currently checking your reported issue with the provided information. We will update you with further details on December 27, 2022.



VS Vijayarasan Sivanandham Syncfusion Team December 27, 2022 05:24 PM UTC

Dinh,

Solution 1:

In our SfDataGrid, all the data operations work depending on the underlying properties(MappingName). Your requirement to sort the custom type column in SfDataGrid can be achieved by define the MappingName like below mentioned,

//Event subscrption

this.sfDataGrid1.AutoGeneratingColumn += OnAutoGeneratingColumn;

//Event customization

 private void OnAutoGeneratingColumn(object sender, Syncfusion.WinForms.DataGrid.Events.AutoGeneratingColumnArgs e)

 {

     //Here customize based on your scenario

     if(e.Column.MappingName == "Advertiser")

     {

         //Here change the MappingName like below mentioned

         e.Column.MappingName = "Advertiser.AdvertiserName";

     }

 }     


UG Link: https://help.syncfusion.com/windowsforms/datagrid/databinding#binding-complex-properties

https://help.syncfusion.com/windowsforms/datagrid/sorting

Solution 2:

SfDataGrid allows to sort the columns based on the custom logic. The custom sorting can be applied by adding the SortComparer instance to SfDataGrid.SortComparers. Refer to the below code snippet,


//Custom Sorting

this.sfDataGrid1.SortComparers.Add(new SortComparer() { Comparer = new CustomComparer(), PropertyName = "Advertiser" });

 

//Here custom sorting for AdvertiserName column

public class CustomComparer : IComparer<object>, ISortDirection

{

    public int Compare(object x, object y)

    {

        int nameX;

        int nameY;

 

        //While data object passed to comparer

        if (x.GetType() == typeof(Book))

        {

            nameX = ((Book)x).Advertiser.AdvertiserName.Length;

            nameY = ((Book)y).Advertiser.AdvertiserName.Length;

        }

 

        //While sorting groups

        else if (x.GetType() == typeof(Group))

        {

            //Calculating the group key length

            nameX = ((Group)x).Key.ToString().Length;

            nameY = ((Group)y).Key.ToString().Length;

        }

 

        else

        {

            nameX = x.ToString().Length;

            nameY = y.ToString().Length;

        }

 

        //returns the comparison result based in SortDirection.

        if (nameX.CompareTo(nameY) > 0)

            return SortDirection == ListSortDirection.Ascending ? 1 : -1;

 

        else if (nameX.CompareTo(nameY) == -1)

            return SortDirection == ListSortDirection.Ascending ? -1 : 1;

 

        else

            return 0;

    }

    private ListSortDirection _SortDirection;

 

    /// <summary>

    /// Gets or sets the property that denotes the sort direction.

    /// </summary>

    /// <remarks>

    /// SortDirection gets updated only when sorting the groups. For other cases, SortDirection is always ascending.

    /// </remarks>

    public ListSortDirection SortDirection

    {

        get { return _SortDirection; }

        set { _SortDirection = value; }

    }

}


UG Link: https://help.syncfusion.com/windowsforms/datagrid/sorting#custom-sorting

Find the sample in the attachment.

If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.


Attachment: SfDataGridDemo_EF_3469358d.zip

Marked as answer

DI Dinh replied to Vijayarasan Sivanandham December 28, 2022 03:21 AM UTC

Thanks,  Vijayarasan,

I will try your solution 2.



VS Vijayarasan Sivanandham Syncfusion Team December 28, 2022 08:27 AM UTC

Dinh,

We are glad to know that the reported problem has been resolved at your end. Please let us know if you have any further queries on this. We are happy to help you
😊.


Loader.
Live Chat Icon For mobile
Up arrow icon