I was looking for a way to sort a DataGridView that has been populated using a Generic List without having to add any dependencies, adding extra classes, or having to change the datatype of my List.
I have checked a few thread such as C# DataGridView sorting with Generic List as underlying source and https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms993236(v=msdn.10)?redirectedfrom=MSDN but it is just too much code to add for the simple funcionality I want to add
The solution I found was to create a simple function that gets called when the user clicks on the column header.
If the datagridview is already sorted ascending by that column, it will sort it descending.
private void orderDataGridView(int columnIndex)
{
List<DataGridViewRow> tmp = (from item in dgv.Rows.Cast<DataGridViewRow>()
orderby item.Cells[columnIndex].Value ascending
select item).ToList<DataGridViewRow>();
if (tmp.Select(x => x.DataBoundItem).Cast<YOURCLASS>().ToList<YOURCLASS>().SequenceEqual(this.dgv.DataSource as List<YOURCLASS>))
{
tmp = (from item in dgv.Rows.Cast<DataGridViewRow>()
orderby item.Cells[columnIndex].Value descending
select item).ToList<DataGridViewRow>();
}
this.dgv.DataSource = tmp.Select(x => x.DataBoundItem).Cast<YOURCLASS>().ToList();
}
private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
orderDataGridView(e.ColumnIndex);
}