如何更改列表视图的列顺序 [英] How to change order of columns of listview
本文介绍了如何更改列表视图的列顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用C#更改listview的列顺序? 最后一列必须是第一列,第一列必须是最后一列.
How to change order of columns of listview with C#? the last column must be the first and the first column must be the last.
I have a listview like this
name age school phone job
---- --- ------ ----- ---
helen 18 KTU 5224511 student
sarah 25 hitan 2548441 engineer
david 19 havai 2563654 student
I want to make this like that
name job phone school age
---- --- ----- ----- ---
helen student 5224511 KTU 18
sarah engineer 2548441 hitan 25
david student 2563654 havai 19
推荐答案
似乎您只需要按所需的显示顺序设置(重新排列)列即可:
It seems that you have just to set (re-arrange) columns in desired display order:
// Job (2nd column to display)
myListView.Columns[4].DisplayIndex = 1;
// Phone (3d column to display)
myListView.Columns[3].DisplayIndex = 2;
// School (4th)
myListView.Columns[2].DisplayIndex = 3;
// Age (5th)
myListView.Columns[1].DisplayIndex = 4;
您还可以使用一些更详细的代码:
You can use a little bit more elaborated code as well:
public static void ArrangeColumns(ListView listView, params String [] order) {
listView.BeginUpdate();
try {
for (int i = 0; i < order.Length; ++i) {
Boolean found = false;
for (int j = 0; j < listView.Columns.Count; ++j) {
if (String.Equals(listView.Columns[j].Text, order[i], StringComparison.Ordinal)) {
listView.Columns[j].DisplayIndex = i;
found = true;
break;
}
}
if (!found)
throw new ArgumentException("Column " + order[i] + " is not found.", "order");
}
}
finally {
listView.EndUpdate();
}
}
...
ArrangeColumns(myListView, "name", "job", "phone", "school", "age");
最后,如果您想重新排列SubItem(移动数据,不仅查看更改),可以这样:
Finally, if you want to re-arrange SubItems (move data, not only view change) you could do it like that:
public static void SwapSubItems(ListView listView, int fromIndex, int toIndex) {
if (fromIndex == toIndex)
return;
if (fromIndex > toIndex) {
int h = fromIndex;
fromIndex = toIndex;
toIndex = h;
}
listView.BeginUpdate();
try {
foreach (ListViewItem line in listView.Items) {
var subItem = line.SubItems[fromIndex];
line.SubItems.RemoveAt(fromIndex);
line.SubItems.Insert(toIndex, subItem);
if (listView.Columns.Count > toIndex) {
var column = listView.Columns[fromIndex];
listView.Columns.RemoveAt(fromIndex);
listView.Columns.Insert(toIndex, column);
}
}
}
finally {
listView.EndUpdate();
}
}
...
myListView.BeginUpdate();
try {
// Job
SwapSubItems(myListView, 4, 1);
// Phone (now, when Job moved, Phone is a 4th column)
SwapSubItems(myListView, 4, 2);
// School (now, when Job and Phone moved, School is a 4th column)
SwapSubItems(myListView, 4, 3);
}
finally {
myListView.EndUpdate();
}
这篇关于如何更改列表视图的列顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文