Ordering Columns in a DataGridView alphabetically

2.8k views Asked by At

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.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

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:

  1. Create a temporary List to store the columns
  2. Store a temporary copy of your DataGridView
  3. Remove all columns from DataGridView
  4. Sort your columns manually, ignoring the first few you don't want to sort
  5. 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