【问题标题】:DataGridView Using SortableBindingList使用 SortableBindingList 的 DataGridView
【发布时间】:2014-05-14 17:22:52
【问题描述】:

我有一个返回 IList 的函数,它是 DataGridView 的数据源。我了解到 DataGridView 不会对 IList 进行排序。我读了This stackoverflow Q&A 并试图实现SortableBindingList。我一定是做错了什么,因为我的 DataGridView 是空的。我还尝试使用 TextBox 访问 SortableBindingSource 中的元素,但什么也没有。

using Microsoft.SqlServer.Management.Controls;
public partial class Form1 : Form
{
    IBusinessLayer businessLayer;
    IList<Category> categories;
    SortableBindingList<Category> catSortable;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        businessLayer = new BusinessLayer();

        categories = businessLayer.GetAllCategories();
        catSortable = new SortableBindingList<Category>(categories);
        categoryBindingSource.DataSource = catSortable;
        categoryDataGridView.DataSource = categoryBindingSource;

        textBox1.Text = catSortable[0].CategoryName;

    }
}

我检查了 Microsoft.SqlServer.Management.Controls,这看起来对吗?

namespace Microsoft.SqlServer.Management.Controls
{
    public class SortableBindingList<T> : BindingList<T>
    {
        public SortableBindingList();
        public SortableBindingList(IList<T> list);

        protected override bool IsSortedCore { get; }
        protected override ListSortDirection SortDirectionCore { get; }
        protected override PropertyDescriptor SortPropertyCore { get; }
        protected override bool SupportsSortingCore { get; }

        protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction);
        protected override void RemoveSortCore();
    }
}

我非常感谢您的帮助并帮助我学习。感谢大家!

【问题讨论】:

  • 我通过创建自己的 SortableBindingList 类来实现这一点,就像在 stackoverflow 示例中一样。我想使用 Microsoft.SqlServer.Management.Controls.dll。怎么了?

标签: c# winforms sorting datagridview ilist


【解决方案1】:

试试这个 SortableBindingList:

public class SortableBindingList<T> : BindingList<T>
{
    private bool isSortedValue;
    ListSortDirection sortDirectionValue;
    PropertyDescriptor sortPropertyValue;

    public SortableBindingList()
    {
    }

    public SortableBindingList(IList<T> list)
    {
        foreach (object o in list)
        {
            this.Add((T)o);
        }
    }

    protected override void ApplySortCore(PropertyDescriptor prop,
        ListSortDirection direction)
    {
        Type interfaceType = prop.PropertyType.GetInterface("IComparable");

        if (interfaceType == null && prop.PropertyType.IsValueType)
        {
            Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);

            if (underlyingType != null)
            {
                interfaceType = underlyingType.GetInterface("IComparable");
            }
        }

        if (interfaceType != null)
        {
            sortPropertyValue = prop;
            sortDirectionValue = direction;

            IEnumerable<T> query = base.Items;

            if (direction == ListSortDirection.Ascending)
            {
                query = query.OrderBy(i => prop.GetValue(i));
            }
            else
            {
                query = query.OrderByDescending(i => prop.GetValue(i));
            }

            int newIndex = 0;
            foreach (object item in query)
            {
                this.Items[newIndex] = (T)item;
                newIndex++;
            }

            isSortedValue = true;
            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }
        else
        {
            throw new NotSupportedException("Cannot sort by " + prop.Name +
                ". This" + prop.PropertyType.ToString() +
                " does not implement IComparable");
        }
    }

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

    protected override ListSortDirection SortDirectionCore
    {
        get { return sortDirectionValue; }
    }

    protected override bool SupportsSortingCore
    {
        get { return true; }
    }

    protected override bool IsSortedCore
    {
        get { return isSortedValue; }
    }
}

【讨论】:

  • 与我现在使用的非常相似。你的似乎更“苗条”并抛出 NotSupportedException。感谢您的快速回复!为什么 C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Release\x64 中的 Microsoft.SqlServer.Management.Controls.dll 为空且不起作用
  • @waltmagic 我想试试它是如何为我工作的,但现在我在导入 Microsoft.SqlServer.Management.Controls.dll 时遇到了项目架构和处理器架构的兼容性问题它根本不会运行:)
  • 我也收到了这个警告。我将安装 32 位版本的 SQL Server 或从我的一台服务器上窃取 Microsoft.SqlServer.Management.Controls.dll,看看这是否会有所作为。谢谢!
  • 这个 SortableBindingList 解决了我一直在使用的不同实现的问题。那个不允许我添加项目。我确实注意到 ArrayList 变量似乎没有被使用。
  • 如果你的查询实现了IEnumerable&lt;T&gt;,为什么你使用foreach(object item in query)而不是foreach(T item in query)?
【解决方案2】:

试试这个,不要忘记将 SortMode 设置为列。此 SortableBindingList 在重新打开时保留元素的原始顺序。

public class SortableBindingList<T> : BindingList<T>
{
    // reference to the list provided at the time of instantiation
    private List<T> _originalList;
    private ListSortDirection? _sortDirection;
    private PropertyDescriptor _sortProperty;

    protected override bool IsSortedCore => _sortDirection != null;
    protected override bool SupportsSortingCore => true;
    protected override ListSortDirection SortDirectionCore => _sortDirection ?? ListSortDirection.Ascending;
    protected override PropertyDescriptor SortPropertyCore => _sortProperty;

    public SortableBindingList()
    {
        _originalList = new List<T>();
    }

    public SortableBindingList(List<T> list)
    {
        _originalList = list;
        ResetItems(_originalList);
    }

    public void Sort(PropertyDescriptor property, ListSortDirection direction) => this.ApplySortCore(property, direction);

    protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
    {
        _sortProperty = property;
        _sortDirection = direction;

        if (!(Items is List<T> items))
            return;

        items.Sort((left, right) =>
        {
            var compareRes = Compare(left == null ? null : _sortProperty.GetValue(left),
                                        right == null ? null : _sortProperty.GetValue(right));
            if (_sortDirection == ListSortDirection.Descending)
                return -compareRes;
            return compareRes;
        });

        ResetBindings();
    }

    private static int Compare(object lhs, object rhs)
    {
        if (lhs == null)
            return rhs == null ? 0 : -1;
        if (rhs == null)
            return 1;
        if (lhs is IComparable comparable)
            return comparable.CompareTo(rhs);
        return lhs.Equals(rhs) ? 0 : string.Compare(lhs.ToString(), rhs.ToString(), StringComparison.Ordinal);
    }

    protected override void RemoveSortCore()
    {
        _sortDirection = null;
        ResetItems(_originalList);
    }

    private void ResetItems(List<T> items)
    {
        base.ClearItems();

        for (var i = 0; i < items.Count; i++)
        {
            base.InsertItem(i, items[i]);
        }
    }

    protected override void OnListChanged(ListChangedEventArgs e)
    {
        _originalList = Items.ToList();
    }
}

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2017-01-25
    • 2015-10-06
    • 2015-09-03
    • 2015-03-25
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多