Ordering Columns in a DataGridView alphabetically
-
13-09-2019 - |
Question
I am using a DataGridView control in a VB.Net application where columns are being added dynamically to a DataTable which is being created in code. I need to order some of the columns alphabetically by name.
E.g.
Name, Surname, House Number, B, D, A, C
I need as...
Name, Surname, House Number, A, B, C, D
the columns are as they are needed so I cannot order them before.
Solution
It's not VB.NET, but this question in C# should have the answer you need: How can I sort the column headers in a datagrid alphabetically
DisplayIndex
is key.
If you don't want to do Linq, then you can implement code to do the following:
- Create a temporary List to store the columns
- Store a temporary copy of your DataGridView
- Remove all columns from DataGridView
- Sort your columns manually, ignoring the first few you don't want to sort
- Add columns back to DataGridView in the correct order using DisplayIndex.
There is also a question here discussing how to change datagrid columns order or index
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow