我还有ListView的另一个问题:(现在我需要移动组中的项目(向上,向下,到开头,到结尾),但ListView始终在最后显示移动的项目。
以下是将项目移至开头的示例代码:
if (1 == listView1.SelectedItems.Count)
{
ListViewItem item = listView1.SelectedItems[0];
ListViewGroup gp = item.Group;
int index;
index = item.Index;
if (index < listView1.Items.Count)
{
index = 0;
listView1.Items.Remove(item);
item.Group = gp;
listView1.Items.Insert(index, item);
}
}
我尝试谷歌找到一些解决方案,我发现其他人(http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/838f90cd-33d8-4c81-9ed9-85220b511afe)有类似我的问题,但他的解决方案无效:(
我考虑使用ObjectListView,但我修改了ListView女巫现在支持drag&amp;使用WinAmp效果,onScroll事件,滚动同步等等。我不想丢失这些东西:(
答案 0 :(得分:2)
试试这个:
/// <summary>
/// Move the given item to the given index in the given group
/// </summary>
/// <remarks>The item and group must belong to the same ListView</remarks>
public void MoveToGroup(ListViewItem lvi, ListViewGroup group, int indexInGroup) {
group.ListView.BeginUpdate();
ListViewItem[] items = new ListViewItem[group.Items.Count + 1];
group.Items.CopyTo(items, 0);
Array.Copy(items, indexInGroup, items, indexInGroup + 1, group.Items.Count - indexInGroup);
items[indexInGroup] = lvi;
for (int i = 0; i < items.Length; i++)
items[i].Group = null;
for (int i = 0; i < items.Length; i++)
group.Items.Add(items[i]);
group.ListView.EndUpdate();
}
答案 1 :(得分:0)
我对此问题的自动回复是检查并查看是否有效(如果您说
) listView1.Items.Count - 1
因为列表是零索引的,因此计数比最后一个索引大1)
答案 2 :(得分:0)
查看代码,它有一些问题让我很好奇。看起来问题可能是intial if语句。如果项目列表中只有一个项目,那么删除它并重新添加它将不会做任何事情,无论你在哪里坚持它。我相信你想要&lt; =
此外,您从您感兴趣的项目中获取索引后立即将索引设置为0.如果代码应该将其移动到顶部,则应在if语句中移动Index = 0。 / p>
不确定这些是否会解决问题......