【问题标题】:How to sort data from DataGridView with automatically generated columns from BindingList?如何使用 BindingList 中自动生成的列对 DataGridView 中的数据进行排序?
【发布时间】:2011-04-07 04:27:11
【问题描述】:

我有一个DataGridView 接收一个BindingList

dataGrid.DataSource = new BindingList<Value>(ValueList);

之后我尝试设置SortMode

dataGrid.Columns.OfType<DataGridViewColumn>().ToList()
    .ForEach(c =>
    {
        c.SortMode = DataGridViewColumnSortMode.Automatic;
    });

断点确实停在上面,但我的DataGridView 不可排序...我尝试单击标题,但没有任何反应。

这些列是自动生成的,我该怎么做才能对数据进行排序?

【问题讨论】:

标签: c# winforms sorting datagridview


【解决方案1】:

我认为问题在于您需要创建一个自定义绑定列表来实现必要的排序功能,以便 DataGridView 知道如何对每一列进行排序。

这篇文章提供了有关如何进行排序的有用信息:

http://xiaonanstechblog.blogspot.com/2009/03/how-to-enable-column-sorting-on.html

如果您想同时进行过滤和排序,您可能需要自定义实现 IBindingListView 接口:

http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglistview.aspx

【讨论】:

    【解决方案2】:

    DataGridView 绑定到 DataSource (DataView, BindingSource, Table, DataSet+"tablename") 在所有情况下它都引用 DataSource强>数据视图。获取此 DataView 的引用并根据需要设置 Sort(和 Filter):

    DataView dv = null;
    CurrencyManager cm = (CurrencyManager)(dgv.BindingContext[dgv.DataSource, dgv.DataMember]);
    
    if (cm.List is BindingSource)
    {
        // In case of BindingSource it may be chain of BindingSources+relations
        BindingSource bs = (BindingSource)cm.List;
        while (bs.List is BindingSource)
        { bs = bs.List as BindingSource; }
    
        if (bs.List is DataView)
        { dv = bs.List as DataView; }
    }
    else if (cm.List is DataView)
    {
        // dgv bind to the DataView, Table or DataSet+"tablename"
        dv = cm.List as DataView;
    }
    
    if (dv != null)
    {
        dv.Sort = "somedate desc, firstname";
        // dv.Filter = "lastname = 'Smith' OR lastname = 'Doe'";
    
        //  You can Set the Glyphs something like this:
        int somedateColIdx = 5;    // somedate
        int firstnameColIdx = 3;   // firstname
        dgv.Columns[somedateColIdx].HeaderCell.SortGlyphDirection = SortOrder.Descending;
        dgv.Columns[firstnameColIdx].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
    }
    

    注意:Sort和Filter中使用的列名对应DataTable中的列名, DataGridView 中的列名是用于在 dgv 中显示单元格的控件的名称。 您可以像这样获取 DataView 中使用的列名:

    string colName = dgv.Columns[colIdx].DataPropertyName
    

    取决于您希望如何跟踪已排序的列(colSequence、colName、asc/desc、dgvColIdx),您可以决定如何构建排序和过滤表达式并在 dgv 中设置 SortGlyph(为了简单起见,我做了硬编码)。

    【讨论】:

      猜你喜欢
      • 2011-07-07
      • 2012-04-27
      • 2017-09-20
      • 1970-01-01
      • 2010-12-14
      • 2019-09-23
      • 2017-02-04
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多