How can I sort the column headers in a datagrid in alphabetical order? WITH#

I have a sorted list containing column headers, how do I change the order of the datagridview so that it is in the same order as the sorted list?

I tried the code below, but this does not always work, some columns are not sorted correctly. Thanks for any help with this.

sortedColumnNames.Sort(); foreach (DataGridViewColumn col in dataGridView1.Columns) { col.DisplayIndex = sortedColumnNames.IndexOf(col.HeaderText); } 

sortedColumnNames: Athens Crete Corfu Kefalonia Mykonos Rhodes Santorini Skiathos Zante

+4
source share
3 answers

I can’t say if your problem is that SortedColumnNames not sorting properly (it’s not), or if the columns are assigned a different order than the one displayed in the list.

If this is the latter, perhaps this is possible because you reorder the items in the collection when you repeat it. Although I do not see this happening in any of the tests that I perform.

As a rule, I do not interfere with the membership or order of the collection that I am repeating. I implement column sorting as follows:

 void SortDataGridViewColumns(DataGridView dgv) { var list = from DataGridViewColumn c in dgv.Columns orderby c.HeaderText select c; int i = 0; foreach (DataGridViewColumn c in list) { c.DisplayIndex = i++; } } 
+3
source

This seems to work. I just wrote a quick test application and it worked fine. Can you nail exactly when it works and when not? When you say that they do not work, are the same columns that always fail?

0
source

You can do it as follows:

  • Add all columns to tmpColumns list
  • Delete all columns from dgv.Columns
  • Sort tmpColumns by name
  • Add columns back to dgv.Columns from tmpColumns and set DisplayIndex while for the following values ​​0,1,2 etc.

It is not perfect, but it works.

0
source

All Articles