views:

139

answers:

1

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.

A: 

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

0A0D