开发者

How can I reorder columns in a listview with the same result as drag and drop

开发者 https://www.devze.com 2022-12-08 18:49 出处:网络
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 displ开发者_运维知识库

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 displ开发者_运维知识库ay 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.


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'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 threw 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


Here's a fun trick. Set up the listview in design mode with first and second columns swapped. Then swap the columns back to desired order when the form loads at runtime. The net effect is that label edits will be available on the second column.

Set the following to true AllowLabelEdit AllowColumnReorder

Edit the columns in design mode, and swap order of first and second column. This initializes the list with label edits for the second column (which is now in displayindex zero.) Then when the form initializes, swap the order of the columns. form load... //reverse the order of the columns listView1.Columns[0].DisplayIndex = 1; listView1.Columns[1].DisplayIndex = 0;

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消