views:

327

answers:

2

How do I reorder the column headers in code AS IF I have clicked and dragged them around?

When AllowColumnReorder is true on a ListView you can drag around the columns, and the display index is changed. When you add new items to the listview, you don't have to worry about how the columns were rearranged, it lines up the incoming data with the original column order.

Basically I am looking for an easy way to save the display indexes, and then restore them when the listview is used again. But I prefer to keep my original column order for inserting data.

+1  A: 

As with almost all ListView tasks, ObjectListView (an open source wrapper around .NET WinForms ListView) has methods to make this easier. Specifically, it has SaveState() and RestoreState() methods, which save (among other things) the order of the columns.

You basically take a copy of the columns as they are, clear the Columns collection, set DisplayIndex correctly on your copy of the columns, and then add all the columns back again.

Grammarian
+1  A: 

Grammarian's response gave me an idea. After adding all the columns in their default order I just cycle through them and read their saved position.

for (int ix = 0; ix < listView.Columns.Count; ix++)
{
  ColumnHeader columnHeader = listView.Columns[ix];
  int displayIndex = Settings.GetSettingInt("List", columnHeader.Text + "Index");
  columnHeader.DisplayIndex = displayIndex;
}

Intellisense through me off, because on DisplayIndex is says

Gets the display order of the column relative to the currently displayed columns

Which made me think it was read only. It isn't. Usually intellisense will say

Gets or sets

Jack B Nimble

related questions