Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3319314
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T22:48:36+00:00 2026-05-17T22:48:36+00:00

I have a class which inherits from BindingList to apply sorting to a bindinglist.

  • 0

I have a class which inherits from BindingList to apply sorting to a bindinglist. The sorting works fine, but when I add or remove an item from the list the bounded control isn’t updated. I think i miss something in the class, but I don’t know what.

I’ve found the code of the class somewhere online, but I don’t know where I found it. My question is, why does this class doesn’u update my control when I update or remove items from the list?

Here is the complete class

public class SortableBindingList<T> : BindingList<T>
{
    #region Membar variables
    private bool _isSortedValue;
    private ArrayList _sortedList;
    private ArrayList _unsortedItems;
    private PropertyDescriptor _sortPropertyValue;
    private ListSortDirection _sortDirectionValue;
    #endregion

    #region Constructor
    public SortableBindingList()
    {
    }

    public SortableBindingList(IList<T> list):base(list)
    {
    }
    #endregion

    #region Overrided Properties
    protected override bool SupportsSearchingCore
    {
        get { return true; }
    }
    protected override bool SupportsSortingCore
    {
        get { return true; }
    }
    protected override bool IsSortedCore
    {
        get { return _isSortedValue; }
    }

    protected override PropertyDescriptor SortPropertyCore
    {
        get { return _sortPropertyValue; }
    }

    protected override ListSortDirection SortDirectionCore
    {
        get { return _sortDirectionValue; }
    }
    #endregion

    #region Public methods
    public int Find(string property, object key)
    {
        // Check the properties for a property with the specified name.
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        PropertyDescriptor prop = properties.Find(property, true);

        // If there is not a match, return -1 otherwise pass search to
        // FindCore method.
        if (prop == null)
            return -1;
        else
            return FindCore(prop, key);
    }

    public void RemoveSort()
    {
        RemoveSortCore();
    }

    public void Sort(string property, ListSortDirection direction)
    {
        // Get all the properties of the object T
        PropertyDescriptorCollection properties = 
            TypeDescriptor.GetProperties(typeof(T));

        // Find the specified property in de collection and ignore case
        PropertyDescriptor prop = properties.Find(property, true);

        if (prop != null)
            ApplySortCore(prop, direction);
    }
    #endregion

    #region Overrided methods
    // The FindCore method searches a list and returns the index of a found item
    protected override int FindCore(PropertyDescriptor prop, object key)
    {
        // Get the property info for the specified property.
        PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
        T item;

        if (key != null)
        {
            // Loop through the items to see if the key
            // value matches the property value.
            for (int i = 0; i < Count; ++i)
            {
                item = (T)Items[i];
                if (propInfo.GetValue(item, null).Equals(key))
                    return i;
            }
        }
        return -1;

    }

    protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
    {
        _sortedList = new ArrayList();

        // Check to see if the property type we are sorting by implements
        // the IComparable interface.
        Type interfaceType = prop.PropertyType.GetInterface("IComparable");

        if (interfaceType != null)
        {
            // If so, set the SortPropertyValue and SortDirectionValue.
            _sortPropertyValue = prop;
            _sortDirectionValue = direction;

            _unsortedItems = new ArrayList(this.Count);

            // Loop through each item, adding it the the sortedItems ArrayList.
            foreach (Object item in this.Items)
            {
                _sortedList.Add(prop.GetValue(item));
                _unsortedItems.Add(item);
            }
            // Call Sort on the ArrayList.
            _sortedList.Sort();
            T temp;

            // Check the sort direction and then copy the sorted items
            // back into the list.
            if (direction == ListSortDirection.Descending)
                _sortedList.Reverse();

            for (int i = 0; i < this.Count; i++)
            {
                int position = Find(prop.Name, _sortedList[i]);
                if (position != i)
                {
                    temp = this[i];
                    this[i] = this[position];
                    this[position] = temp;
                }
            }

            _isSortedValue = true;

            // Raise the ListChanged event so bound controls refresh their
            // values.
            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }
        else
            // If the property type does not implement IComparable, let the user
            // know.
            throw new NotSupportedException("Cannot sort by " + prop.Name +
                ". This" + prop.PropertyType.ToString() +
                " does not implement IComparable");

    }

    protected override void RemoveSortCore()
    {
        int position;
        object temp;

        // Ensure the list has been sorted.
        if (_unsortedItems != null)
        {
            // Loop through the unsorted items and reorder the
            // list per the unsorted list.
            for (int i = 0; i < _unsortedItems.Count; )
            {
                position = this.Find(_sortPropertyValue.Name,
                    _unsortedItems[i].GetType().GetProperty(_sortPropertyValue.Name).GetValue(_unsortedItems[i], null));

                if (position > 0 && position != i)
                {
                    temp = this[i];
                    this[i] = this[position];
                    this[position] = (T)temp;
                    i++;
                }
                else if (position == i)
                    i++;
                else
                    // If an item in the unsorted list no longer exists,
                    // delete it.
                    _unsortedItems.RemoveAt(i);
            }

            _isSortedValue = false;

            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

    }
    #endregion
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T22:48:37+00:00Added an answer on May 17, 2026 at 10:48 pm

    Cannot reproduce; it seems fine here:

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Button btn;
            var data = new SortableBindingList<Foo> { new Foo { Bar = "abc" } };
            using (var form = new Form
            {
                Controls = {
                    (btn = new Button { Dock = DockStyle.Bottom, Text = "add"}),
                    new DataGridView { Dock = DockStyle.Fill, DataSource = data,
                        AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells }
                }
            })
            {
                btn.Click += delegate { data.Add(new Foo { Bar = DateTime.Now.Ticks.ToString()}); };
                Application.Run(form);
            }
        }
    }
    class Foo
    {
        public string Bar { get; set; }
    }
    

    Can you give a reproducible example where it doesn’t update?


    Re the comments: the code is using something comparable to:

    data = new BindingList<Foo>(someOtherData.Where(lambda).ToList());
    

    Now, if we add to someOtherData, we indeed won’t notice any difference. A slight peculiarity of Collection<T> is that if you pass a list into the constructor, that list does become the actual backing list, but:

    a: it can’t raise any events unless it knows about it; the only way it can know is if it sees the addition, i.e. the addition goes through BindingList<T>.Add, not the backing list’s Add. This can cause the odd effect that reloading or rebinding the data can make items magically appear (in some cases, not this one).

    b: in this case, the backing list is not someOtherData, but a separate list generated by LINQ (ToList()), so even adding something to someOtherData will never cause the binding-lists backing list to see the new item.

    In short: you need to treat the binding-list as the “master” if you expect data changes to propagate. Else; re-bind the data.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class which inherits from QTreeWidgetItem and I intercept the click event.
I have class Foo which defines property Id . Class Bar inherits from Foo
I have a class which I'm serialising to send over a unix socket and
I have a class which implements UserControl. In .NET 2005, a Dispose method is
I have a class which is marked with a custom attribute, like this: public
I have a class which has the following constructor public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent();
I have a class which looks something like this: public class Test { private
I have a class which constructor takes a Jakarta enums . I'm trying to
I have a class which is not thread safe: class Foo { /* Abstract
I have a class which has many small functions. By small functions, I mean

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.