Home > database >  dataGridView.Sort error System.InvalidOperationException: 'The DataGridView control must be bou
dataGridView.Sort error System.InvalidOperationException: 'The DataGridView control must be bou

Time:09-22

I followed some examples I found but the line that does the sorting doesn't work. Below is the code example:

List<GridData> data = new List<GridData>() { 
            new GridData { name="test1", address="a", id=1, phone=1 },
           new GridData { name="test6", address="f", id=3, phone=6 },
           new GridData { name="test10", address="c", id=6, phone=8 },
           new GridData { name="test8", address="z", id=8, phone=10 },
           new GridData { name="test0", address="o", id=10, phone=12 }
        };

        dataGridView1.DataSource = data;
        dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);

CodePudding user response:

You need to use an object that implements an IBindingList.

I use a generic class to do this, with code I found and share with you. In your case it would be like this:

SortableBindingList<GridData> data = new SortableBindingList<GridData>();

        data.Add(new GridData { name = "test1", address = "a", id = 1, phone = 1 });
        data.Add(new GridData { name = "test6", address = "f", id = 3, phone = 6 });
        data.Add(new GridData { name = "test10", address = "c", id = 6, phone = 8 });
        data.Add(new GridData { name = "test8", address = "z", id = 8, phone = 10 });
        data.Add(new GridData { name = "test0", address = "o", id = 10, phone = 12 });

        dataGridView1.DataSource = data;
        dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);

Here the code of the generic class "SortableBindingList", created by "Michel Posseth":

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace WindowsApp2
{
    public class SortableBindingList<T> : BindingList<T>
    {
        private bool IsSorted { get; set; }
        private ListSortDirection SortDirection { get; set; }
        private PropertyDescriptor SortProperty { get; set; }
        protected override bool SupportsSortingCore
        {
            get
            {
                return true;
            }
        }
        protected override ListSortDirection SortDirectionCore
        {
            get
            {
                return SortDirection;
            }
        }protected override PropertyDescriptor SortPropertyCore
    {
        get
        {
            return SortProperty;
        }
    }
    protected override void ApplySortCore(PropertyDescriptor PDsc, ListSortDirection Direction)
    {
        List<T> items = Items as List<T>;
        if (items is null)
        {
            IsSorted = false;
        }
        else
        {
            var PCom = new PCompare<T>(PDsc.Name, Direction);
            items.Sort(PCom);
            IsSorted = true;
            SortDirection = Direction;
            SortProperty = PDsc;
        }
        OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
    }
    protected override bool IsSortedCore
    {
        get
        {
            return IsSorted;
        }
    }
    protected override void RemoveSortCore()
    {
        IsSorted = false;
    }
    #region  Constructors 
    public SortableBindingList(ICollection<T> list) : base((IList<T>)list)
    {
    }
    public SortableBindingList() : base()
    {
    }
    #endregion
    #region  Property comparer 
    private class PCompare<T> : IComparer<T>
    {
        private PropertyInfo PropInfo { get; set; }
        private ListSortDirection SortDir { get; set; }
        internal PCompare(string SortProperty, ListSortDirection SortDirection)
        {
            PropInfo = typeof(T).GetProperty(SortProperty);
            SortDir = SortDirection;
        }
        internal int Compare(T x, T y)
        {
            return SortDir == ListSortDirection.Ascending ? Comparer.Default.Compare(PropInfo.GetValue(x, null), PropInfo.GetValue(y, null)) : Comparer.Default.Compare(PropInfo.GetValue(y, null), PropInfo.GetValue(x, null));
        }

        int IComparer<T>.Compare(T x, T y) => Compare(x, y);
    }
    #endregion

}
}
  • Related