17
votes

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?

2
are the columns set to create automatically in the Grid? that's the only thing that I can think of .. it's the AuoGenerate Columns property I believe..MethodMan
Setting AutoGenerateColumns to false and manually adding columns doesn't help either. I want to avoid manually creating columns and rows in DataGridView because of performance issues.mandrive
if you are manually creating the columns then it sounds to me like you will need to manually create them in code as well as using the new key word to create the columns if I am following what you are saying in your original questionMethodMan

2 Answers

64
votes

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.

2
votes

.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());