问题描述
我有一个数据绑定的DataGridView,我正在尝试使用IComparer进行排序.
I have a data-bound DataGridView that I am trying to sort using an IComparer.
当我尝试进行排序时,出现此错误:
When I try to apply my sort I get this error:
我的排序技术基于此链接.
仅供参考,我试图通过使用位图的标记值来比较位图.
Just an FYI I am trying to compare Bitmaps by using their tag values.
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;
}
推荐答案
据我所知,无法使用链接文章上显示的方法对数据绑定的DatagridView进行排序.
As far as I know, databound DatagridView cannot be sorted using the methods shown on the linked article.
您想要做的是对基础容器进行排序.如果您使用的是数据表,则无法直接对其进行排序.
What you want to do is sort the underlying container. If you're using a DataTable, you can't sort it directly.
您可以做的是使用Linq的OrderBy并将其传递给您的自定义比较器.之后,在linq查询上调用AsDataView()并将您的DataGridView绑定到该DataView.
What you can do is use Linq's OrderBy and pass it your custom comparer. After that, call AsDataView() on your linq query and bind your DataGridView to this DataView.
类似这样的东西:
RowComparer comp = new RowComparer();
var query = northwindDataSet.Customers.AsEnumerable().OrderBy(q => q, comp);
DataView dv = query.AsDataView();
customersBindingSource.DataSource = dv;
请注意,在此示例中,我使用的是DataTable和BindingSource,但您应该了解一下:-)
Note that I'm using a DataTable and a BindingSource in this example, but you should get the idea :-)
希望这会有所帮助
这篇关于IComparer对数据绑定Datagridview进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!