【问题标题】:Sort DataGridView without changing Datasource/BindingList order在不更改 Datasource/BindingList 顺序的情况下对 DataGridView 进行排序
【发布时间】:2018-05-20 11:48:54
【问题描述】:

我有一个 C# 自定义 MySortableBindingList : BindingList<MyClass> 它实现了所有用于排序的东西(SupportsSortingCore, SortPropertyCore, ApplySortCore(...) 等),其中MyClass : INotifyPropertyChanged

因此,我可以将此列表用于 Forms DataGridView (myDataGridView1.DataSource = mySortableBindingList1),并根据列/属性在我的 GUI 中对 DataGridView 进行排序。

现在的问题是: 我可以定义 UI DataGridView 的排序如何影响 MySortableBindingList 的顺序吗?

因为现在对 GridView 进行排序也会对 BindingList 进行排序,但我需要保持内部(原始)顺序,因为我需要使用存储的索引来访问列表。

提前谢谢你!

【问题讨论】:

    标签: c# forms datagridview bindinglist


    【解决方案1】:

    我相信这与您的排序实现有关,导致了这种情况。我的建议是关注Chris Dogget's suggestion 并下载开源BindingListView

    用法很简单:

    BindingList<Example> examples = new BindingList<Example>()
    {
        new Example() { Foo = "foo1", Bar = "bar2" ),
        new Example() { Foo = "foo2", Bar = "bar4" ),
        new Example() { Foo = "foo3", Bar = "bar1" ),
        new Example() { Foo = "foo4", Bar = "bar3" ),
    };
    
    BindingListView blv = new BindingListView(examples);
    dataGridView1.DataSource = blv;
    

    排序被烘焙并以原始顺序保留基础列表。使用之前的数据,我们可以遍历源和DataGridView 并打印出结果,看看它们是不同的。我们将使用for 循环来演示您请求的索引:

    BindingListView<Example> blv = this.dataGridView1.DataSource as BindingListView<Example>;
    BindingList<Example> examples = examples.DataSource as BindingList<Example>;
    
    Console.WriteLine("From BindingListView:");
    for (int i = 0; i < examples.Count; i++)
    {
        Example ex = examples[i];
        Console.WriteLine($"{ex.Foo} {ex.Bar}");
    }
    
    Console.WriteLine("\nFrom DataGridView:");
    
    for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
    {
        DataGridViewRow row = this.dataGridView1.Rows[i];
        Console.WriteLine($"{row.Cells["Foo"].Value} {row.Cells["Bar"].Value}");
    }
    

    DataGridView 已按Bar 列排序时的输出:

    /*
    From BindingListView:
    foo1 bar2
    foo2 bar4
    foo3 bar1
    foo4 bar3
    
    From DataGridView:
    foo3 bar1
    foo1 bar2
    foo4 bar3
    foo2 bar4
    */
    

    【讨论】:

    • 谢谢!我会试试这个(好吧,我期望一个 1-2 行的解决方案,而不是一个 2500 行长的项目:P),这个项目似乎有很多额外的功能,所以我会尝试。 (例如,添加项目是否会更新 UI datagridview/INotifyPropertyChanged 是否工作...)
    • 您应该能够只下载 dll 并在您的项目中引用它们。如果我需要“修补”,我只会下载整个 BindingListView 项目。对于您的 UI 更新:使用 BindingList&lt;T&gt; 而不是 List&lt;T&gt;。我已编辑我的答案以反映这一变化。
    猜你喜欢
    • 2020-07-24
    • 2018-11-16
    • 2023-03-28
    • 1970-01-01
    • 2011-05-20
    • 2017-09-20
    • 2021-05-12
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多