【问题标题】:IComparer sort on databound Datagridview数据绑定Datagridview上的IComparer排序
【发布时间】:2012-08-24 17:06:51
【问题描述】:

我有一个数据绑定的 DataGridView,我正在尝试使用 IComparer 对其进行排序。

当我尝试应用我的排序时,我收到了这个错误:

DataGridView 控件是数据绑定的。控件不能使用比较器来执行排序操作。

我的排序技术基于this link

仅供参考,我试图通过使用它们的标记值来比较位图。

public int Compare(object x, object y)
{
    DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
    DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

    // Try to sort based on the tag 
    int CompareResult = System.String.Compare(
        DataGridViewRow1.Cells[1].Tag.ToString(),
        DataGridViewRow2.Cells[1].Tag.ToString());



    return CompareResult * sortOrderModifier;
}

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    据我所知,无法使用链接文章中显示的方法对数据绑定的 DatagridView 进行排序。

    您要做的是对底层容器进行排序。如果您使用的是 DataTable,则无法直接对其进行排序。

    您可以做的是使用 Linq 的 OrderBy 并将您的自定义比较器传递给它。之后,在您的 linq 查询上调用 AsDataView() 并将您的 DataGridView 绑定到此 DataView。

    类似这样的:

     RowComparer comp = new RowComparer();
     var query = northwindDataSet.Customers.AsEnumerable().OrderBy(q => q, comp);
     DataView dv = query.AsDataView();
    
     customersBindingSource.DataSource = dv;
    

    请注意,我在此示例中使用了 DataTable 和 BindingSource,但您应该明白这一点 :-)

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 2011-12-25
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多