Reputation: 2452
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:
DataGridView control is data-bound. The control cannot use the comparer to perform the sort operation.
My sorting technique was based off this link.
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;
}
Upvotes: 1
Views: 4167
Reputation: 5380
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.
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.
Something like this:
RowComparer comp = new RowComparer();
var query = northwindDataSet.Customers.AsEnumerable().OrderBy(q => q, comp);
DataView dv = query.AsDataView();
customersBindingSource.DataSource = dv;
Note that I'm using a DataTable and a BindingSource in this example, but you should get the idea :-)
Hope this helps
Upvotes: 3