如何对列表视图中的列进行重新排序,并获得与拖放相同的结果
如何在代码中重新排序列标题(就像我单击并拖动它们一样)?
当 ListView 上的 AllowColumnReorder 为 true 时,您可以在列周围拖动,并且显示索引会更改。当您向列表视图添加新项目时,您不必担心列是如何重新排列的,它会将传入的数据与原始列顺序对齐。
基本上我正在寻找一种简单的方法来保存显示索引,然后在再次使用列表视图时恢复它们。但我更喜欢保留原始列顺序来插入数据。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与几乎所有 ListView 任务一样,ObjectListView(.NET 的开源包装器) WinForms ListView)有方法使这变得更容易。具体来说,它具有
SaveState()
和RestoreState()
方法,用于保存(除其他外)列的顺序。您基本上按原样获取列的副本,清除 Columns 集合,在列副本上正确设置 DisplayIndex,然后再次添加所有列。
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()
andRestoreState()
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.
语法学家的回答给了我一个想法。按默认顺序添加所有列后,我只需循环浏览它们并读取它们保存的位置。
Intellisense 让我失望了,因为 DisplayIndex 上说
这让我认为它是只读的。事实并非如此。通常智能感知会说
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.
Intellisense threw me off, because on DisplayIndex is says
Which made me think it was read only. It isn't. Usually intellisense will say
这是一个有趣的技巧。
在设计模式下设置列表视图,交换第一列和第二列。然后,当表单在运行时加载时,将列交换回所需的顺序。最终效果是第二列上可以进行标签编辑。
将以下内容设置为 true
允许标签编辑
AllowColumnReorder
在设计模式下编辑列,并交换第一列和第二列的顺序。这会初始化
带有第二列标签编辑的列表(现在显示索引为零。)
然后,当表单初始化时,交换列的顺序。
表单加载...
//反转列的顺序
listView1.Columns[0].DisplayIndex = 1;
listView1.Columns[1].DisplayIndex = 0;
希望有帮助。
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.