winforms ListView项未移动

nuypyhwy  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(234)

我正试图通过按钮向上/向下移动选定的ListView项。该项被删除并插入到同一索引处。但我想将其添加到索引+1(向下)或索引-1(向上)处
我有4个项目,并试图向下移动项目2(在索引1处)下面是我的down_click过程的一个示例

  1. private void down_Click(object sender, EventArgs e)
  2. {
  3. ListViewItem selected = listView1.SelectedItems[0];
  4. int sel_index = listView1.SelectedItems[0].Index;
  5. int newindex = sel_index + 1;
  6. listView1.Items.RemoveAt(sel_index);
  7. listView1.Items.Insert(newindex, selected);
  8. }
cbeh67ev

cbeh67ev1#

您只需将listview的视图模式更改为list:

  1. listView1.View = View.List;

我希望这会有帮助。

lhcgjxsq

lhcgjxsq2#

实际上你的代码没有任何问题,问题出在ListView上。
当您使用ListView并将View属性设置为LargIcon(即view属性的默认值)时,SmallIcon或平铺视图(插入项目)不能按预期工作,但在列表视图和详细信息视图中,它可以按预期工作。
要解决此问题,可以执行以下任一操作:

解决方案1:(解决方法)

将ListView的View property设置为“详细信息”或“列表”。

解决方案2:(更好、更完整的解决方案)

要解决所有视图中的问题,请使用此UpdateLayout方法,并在插入项目后调用它。

  1. private void UpdateLayout()
  2. {
  3. if (this.listView1.View == View.LargeIcon ||
  4. this.listView1.View == View.SmallIcon ||
  5. this.listView1.View == View.Tile)
  6. {
  7. listView1.BeginUpdate();
  8. //Force ListView to update its content and layout them as expected
  9. listView1.Alignment = ListViewAlignment.Default;
  10. listView1.Alignment = ListViewAlignment.Top;
  11. listView1.EndUpdate();
  12. }
  13. }

所以UpButton和DownButton的代码可能是这样的:

  1. private void UpButton_Click(object sender, EventArgs e)
  2. {
  3. //If there is a selected item in ListView
  4. if (this.listView1.SelectedIndices.Count >= 0)
  5. {
  6. //If selected item is not the first item in list
  7. if (this.listView1.SelectedIndices[0] > 0)
  8. {
  9. var index = this.listView1.SelectedItems[0].Index;
  10. var item = this.listView1.SelectedItems[0];
  11. this.listView1.Items.RemoveAt(index);
  12. this.listView1.Items.Insert(index - 1, item);
  13. this.UpdateLayout();
  14. }
  15. }
  16. }
  17. private void DownButton_Click(object sender, EventArgs e)
  18. {
  19. //If there is a selected item in ListView
  20. if (this.listView1.SelectedIndices.Count >= 0)
  21. {
  22. //If selected item is not the last item in list
  23. if (this.listView1.SelectedIndices[0] < this.listView1.Items.Count - 1)
  24. {
  25. var index = this.listView1.SelectedItems[0].Index;
  26. var item = this.listView1.SelectedItems[0];
  27. this.listView1.Items.RemoveAt(index);
  28. this.listView1.Items.Insert(index + 1, item);
  29. this.UpdateLayout();
  30. }
  31. }
  32. }

其他附注

若要更好地查看ListView,请在设计器或代码中设置以下属性:

  • MultiSelect设置为false,以防止选择多个项目
  • FullRowSelect设置为true可通过单击行中的任意位置来启用选择
  • 设置HideSelection = false以突出显示选定项,即使ListView没有焦点
展开查看全部

相关问题