I am trying to get the sorting to work for the DataGridView. The sorting should be automatic when I click on the column headers but it is not working. What am I doing wrong?
private void LoadDummyData()
{
List<AddressBookDummy> list = new List<AddressBookDummy>();
list.Add(new AddressBookDummy { Name = "Newman, Alfred", Type = "CAR" });
list.Add(new AddressBookDummy { Name = "Skywalker, Luke", Type = "SUP" });
list.Add(new AddressBookDummy { Name = "Skywalker, Leia", Type = "BEN" });
addressBookGrid.DataSource = list;
}
private void InitializeGrid()
{
addressBookGrid.RowHeadersVisible = false;
addressBookGrid.ScrollBars = ScrollBars.Vertical;
addressBookGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
addressBookGrid.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
addressBookGrid.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
}
You have to bind to a list that implements sorting, here's an example
Summary :
public Form1()
{
InitializeComponent();
SortableBindingList<person> persons = new SortableBindingList<person>();
persons.Add(new Person(1, "timvw", new DateTime(1980, 04, 30)));
persons.Add(new Person(2, "John Doe", DateTime.Now));
this.dataGridView1.AutoGenerateColumns = false;
this.ColumnId.DataPropertyName = "Id";
this.ColumnName.DataPropertyName = "Name";
this.ColumnBirthday.DataPropertyName = "Birthday";
this.dataGridView1.DataSource = persons;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With