【问题标题】:how to change an item index in listview?如何更改列表视图中的项目索引?
【发布时间】:2012-03-28 14:29:03
【问题描述】:

我有一个 listView 和两个按钮(向上、向下),我想向上或向下移动所选项目。
我考虑过在所选项目和上一个项目之间进行交换.. 但我尝试的代码.. 没有意义,因为索引是只读的。
也挖掘或总和不 owrk .. 我根本不能弄乱索引。

private void btnDown_Click(object sender, EventArgs e)
    {
         listView1.SelectedItems[0].Index--; // It's ReadOnly.
    }


那么 .. 我如何让用户能够更改 ListViewItem 索引,就像 VB 如何让我们更改这些项目索引 [如图所示]

提前谢谢...

【问题讨论】:

  • 您应该更改列表源中的顺序
  • 大声笑代码?我应该如何生成代码而不首先从您的代码中看到任何有用的东西? - 你用日期填充列表的源 - 我不知道如何,但你必须 - 这个数据是你应该改变你想要切换的项目的顺序的地方
  • @CarstenKönig 就像 M4N 一样。
  • 好吧,但你从中得到了什么?确定用户会看到更改的顺序,但是这些数据会被持久化吗?我的意思是您的用户可能想要更改订单是有原因的吗? M4N 给出的是 UI 中的 hack - 又名 sphagetti-code - 不是一个好的模式,但继续......

标签: c# winforms listview


【解决方案1】:

你必须先remove the selected item,然后在新位置重新添加。

例如将项目向上移动一个位置:

var currentIndex = listView1.SelectedItems[0].Index;
var item = listView1.Items[index];
if (currentIndex > 0)
{
    listView1.Items.RemoveAt(currentIndex);
    listView1.Items.Insert(currentIndex-1, item);
}

【讨论】:

    【解决方案2】:

    以下是对 M4N 答案的改进,用于处理列表顶部项目的重新排序并使其位于列表底部

    int currentIndex = listView1.SelectedItems[0].Index;
    ListViewItem item = listView1.Items[currentIndex];
    if (currentIndex > 0)
    {
        listView1.Items.RemoveAt(currentIndex);
        listView1.Items.Insert(currentIndex - 1, item);
    }
    else
    {
        /*If the item is the top item make it the last*/
        listView1.Items.RemoveAt(currentIndex);
        listView1.Items.Insert(listView1.Items.Count, item);
    }
    

    【讨论】:

      【解决方案3】:

      如果是可观察的集合,您还可以调用:.Move(currentindex, newindex);

      MSDN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 2023-03-08
        相关资源
        最近更新 更多