mandrive
mandrive

Reputation: 1015

DataGridView automatic sorting doesn't work when datasource bound

My problem is: when I bind datasource to DataGridView

BindingList<Contract> contracts = new BindingList<Contract>(Contract.GetAll());
dgEndingContracts.DataSource = contracts.Where(c => c.ExpirationDate <= nextMonth && c.IsArchived == false).ToList();

and set every column to SortMode = DataGridViewColumnSortMode.Automatic when I click on dataGridView header rows doesn't sort.

But when I manually create each column, create and fill with data each row of dataGridView, and the set column sort mode to automatic, sorting works fine.

What is the difference and how can I enable sorting in first approach?

Upvotes: 21

Views: 40761

Answers (2)

mandrive
mandrive

Reputation: 1015

I 've found solution.

It's seems that DataGridView can't sort either List <T> or BindingList<T>

So I've added class SortedBindingList<T> based on code from: and now my DataGridView can sort columns.

Thanks for help guys.

Upvotes: 71

Slava
Slava

Reputation: 1095

.ToList() doesn't return something that implements IBindingList. Use something, like thtat:

dgEndingContracts.DataSource = new BindingList<Contract>(contracts.Where(c => c.ExpirationDate <= nextMonth && c.IsArchived == false).ToList());

Upvotes: 2

Related Questions