首页 > 解决方案 > (NugetPackage) AdvancedDataGridView 排序/过滤列表

问题描述

介绍一下,我现在有一个数据网格视图,其中填充了列表中的数据。

我想让用户的排序和过滤更容易,所以我开始使用ADGV

它使用像 Excel 那样的排序和过滤类型。现在他们已经完成了所有的方法,但实际的排序/过滤是你需要自己做的事情。

我遵循了一些教程,但它们并没有真正使用 List 作为数据源。在教程中,他们使用排序和筛选方法,而 List 不像他们在教程中那样接受。

有没有办法使用 sortstring/filterstring 对 linq 列表进行排序/过滤,就像他们在此处的视频 (4:45)中所做的那样。

标签: c#winformsdatagridview

解决方案


如果您正在寻找一种内置方式来支持List<T>使用FilterStringSortString生成的排序和过滤AdvancedDataGridView,答案是:不,没有内置方式。过滤器是在生成的ADGVFilterMenu,据我所知,没有办法覆盖过滤器的生成。

但是您可以将您的转换List<T>为 aDataTable并简单地使用这些字符串进行排序和过滤。例如:

private void Form1_Load(object sender, EventArgs e)
{
    var list = db.Products.ToList();
    this.productBindingSource.DataSource = list.ToDataTable(); 
}
private void advancedDataGridView1_SortStringChanged(object sender, EventArgs e)
{
    this.productBindingSource.Sort = advancedDataGridView1.SortString;
}
private void advancedDataGridView1_FilterStringChanged(object sender, EventArgs e)
{
    this.productBindingSource.Filter = advancedDataGridView1.FilterString;
}

在上面的例子中,我使用了这篇文章ToDataTable的扩展方法:

public static class EnumerableExtensions
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, 
                Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
}

推荐阅读