views:

1406

answers:

3

I have a sorted list that contains the column headers, how do I rearrange my datagridview so it is in the same order as my sorted list?

I've tried the code below but this doesn't 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

A: 

Seems like that should work. I just wrote a quick app to test and it worked fine. Can you nail down exactly when it's working and when it isn't? When you say they don't work, is it always the same columns that are out of order?

BFree
+1  A: 

I can't tell if your problem is that SortedColumnNames isn't sorted properly (which it's not), or if the columns are being assigned a different order than what appears in the list.

If it's the latter, it could conceivably be because you're modifying the order of items in the collection as you're iterating over it. Though I'm not seeing that happen in any of the tests I'm running.

Just as a general rule, I don't mess with the membership or order of a collection that I'm iterating over. I implement column-sorting this way:

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++;
    }
}
Robert Rossney
That's something I wouldn't have thought of. Linq.
lb
A: 

You can do it in this way:

  1. Add all columns to List tmpColumns
  2. Remove all columns from dgv.Columns
  3. Sort tmpColumns by name
  4. Add columns back to dgv.Columns from tmpColumns and set while it DisplayIndex to next values 0,1,2 and so on.

It's not ideal, but it works.

tomaszs