Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
mandrive Avatar asked Mar 15 '13 18:03

mandrive


2 Answers

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.

like image 182
mandrive Avatar answered Nov 13 '22 01:11

mandrive


.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());
like image 32
Slava Avatar answered Nov 13 '22 03:11

Slava