Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SortMode in DataGridView

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;
}
like image 881
Greg Finzer Avatar asked Nov 04 '11 17:11

Greg Finzer


1 Answers

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;
}
like image 54
Arjen van der Spek Avatar answered Sep 22 '22 20:09

Arjen van der Spek