【问题标题】:VS: Make BindingList sortableVS:使 BindingList 可排序
【发布时间】:2018-06-14 14:22:11
【问题描述】:

我正在使用 C# 和 Visual Studio 制作一个项目。问题是我正在使用我想要使其可排序的 GridView(在本例中为 Prototype Code 列),我创建了一个按钮来执行此操作:

 void SortButton_Click(Object sender, EventArgs e)
        {
            dataGridView1.Sort(PrototypeCodeDataGridViewTextBoxColumn, System.ComponentModel.ListSortDirection.Ascending);
        }

但是在按下按钮的那一刻,我得到了这个:

System.InvalidOperationException: '一个 DataGridView 控件不能 如果它绑定到不支持的 IBindingList,则排序 排序顺序。'

我有 Prototypes.Datasource,我想这就是我必须更改以使其可排序的,但是如何? 非常感谢您的帮助,谢谢!

【问题讨论】:

    标签: c# visual-studio sorting gridview datasource


    【解决方案1】:

    如您所见,基类BindingListdoes not support 排序。必须自己实现。

    1. 简单的解决方案是派生一个支持排序的新类。看一个简单的例子here

    2. 但就我自己而言,我更喜欢 CSLA's solution,这是对所需接口的全新重新实现,因为它提供了一个排序视图,而不是修改原始的底层集合。

    用法:

    var myBindingSource = new SortedBindingList<MyType>(myCollection);
    myBindingSource.ApplySort(propertyName, ListSortDirection.Ascending);
    dataGridView1.DataSource = myBindingSource;
    

    还请注意,您实际上并不需要创建SortButton,因为如果提供的数据源支持排序,那么DataGridView 标题将是可点击的,它会自动显示排序方向 - 请先查看图片链接。


    2020 年更新:

    去年我把我的库开源了,所以你也可以使用我的SortableBindingList&lt;T&gt;,它也修复了原始BindingListperformance problem。你可以从NuGet下载。

    【讨论】:

    • 最后,我使用了一个过滤数据的函数。现在我在开始时调用它,但没有搜索价值,但带有“分组依据”,所以它总是被过滤,无论如何谢谢!
    • 感谢您将库开源!
    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2010-10-02
    • 2020-05-07
    • 2010-09-19
    • 2011-01-15
    • 2011-01-25
    相关资源
    最近更新 更多