Without knowing the exact error you get, we have to guess - but the most likely is
DataGridView control must be bound to an IBindingList object to be sorted.
Which mans that you have used the list directly as the DataSource for the DGV.
The easiest solution is to convert the List to a DataTable, and use that as the source.
That's a pain, so I wrote this:
Converting a List to a DataTable[
^] to do just that...
Then it's trivial:
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass() { Name = "DDDD", Date = DateTime.Now });
list.Add(new MyClass() { Name = "BBBB", Date = DateTime.Now.AddDays(-1) });
list.Add(new MyClass() { Name = "CCCC", Date = DateTime.Now.AddDays(-2) });
list.Add(new MyClass() { Name = "AAAA", Date = DateTime.Now.AddDays(-3) });
DataTable dt = list.ToDataTable();
dataGridView1.DataSource = dt;
}
private void SortByName_Click(object sender, EventArgs e)
{
dataGridView1.Sort(dataGridView1.Columns["Name"], ListSortDirection.Ascending);
}
private void SortByDate_Click(object sender, EventArgs e)
{
dataGridView1.Sort(dataGridView1.Columns["Date"], ListSortDirection.Ascending);
}
}
...
public class MyClass
{
public string Name { get; set; }
public DateTime Date { get; set; }
}