【问题标题】:How to clear the Subitems on a ListViewItem without clearing the Text?如何在不清除文本的情况下清除 ListViewItem 上的子项?
【发布时间】:2012-01-11 15:56:30
【问题描述】:

我正在尝试清除并重新添加 .net 中 ListViewItemSubItems

private void RefreshItem(ListViewItem item)
{
   item.Text = accountNumber;

   item.SubItems.Clear(); //in case there are any
   item.SubItems.Add(name);    
   item.SubItems.Add(address);
   item.SubItems.Add(phone);
   item.SubItems.Add(workphone);
   item.SubItems.Add(email);
   item.SubItems.Add(idType);
   item.SubItems.Add(idNumber);
   item.SubItems.Add(idExpires);
   ...
}

但清除子项也会清除Text

注意:矛盾的是,清除SubItems 也会清除Text,但添加SubItems 不会同时添加Text

当我只想更新子项时也会出现问题:

private void RefreshItem(ListViewItem item)
{
   item.SubItems.Clear(); //in case there are any
   item.SubItems.Add(location);    
   item.SubItems.Add(date);
   item.SubItems.Add(cashier);
   item.SubItems.Add(totalBuyAmount);
   item.SubItems.Add(totalSellAmount);
   item.SubItems.Add(currencyCode);
   item.SubItems.Add(exchangeRate);
   item.SubItems.Add(isVip);
   ...
}

我怎么能ClearSubItemsListViewItem,却不清除Text

【问题讨论】:

  • 能不能不把Text存入局部变量,把SubItems清空再重新设置Text?也许不是最理想的解决方案。
  • 我不明白您为什么要清除子项而不是与它们关联的文本。
  • @John 我想你可能误解了。 TextListItem 本身的文本。 ListItem 然后可以有子项。我想清除 ListItem.SubItems 集合,但保留 ListItem.Text 属性。
  • @Ian Boyd:试试 adrift 说的话。

标签: c# winforms listview listviewitem


【解决方案1】:

有趣,我从未注意到这种行为。如果没有更简单的方法,我将遍历并删除所有Index 大于0SubItems。索引为0SubItemListViewItem.Text 对应。

有关参考,请参阅SubItems 属性的注释:

ListViewItem.ListViewSubItemCollection 中的第一个子项是 总是拥有子项目的项目。执行操作时 集合中的子项,请务必参考索引位置 1 而不是 0 来更改第一个子项。

【讨论】:

  • 我添加了一个带有(boolean workCorrectly) 参数的扩展方法。它会清除 ListViewItem.SubItems 集合,同时保留 ListViewItem.Text 属性。
【解决方案2】:

为什么不直接更改子项的文本而不是删除和重新添加?

【讨论】:

  • 因为我不知道函数启动时有多少子项
【解决方案3】:

在数据网格视图、列表视图和类似的小部件中刷新数据时,围绕更新使用 SuspendLayout() 和 ResumeLayout() 会非常有用。这将允许您进行所需的任何清理或操作,而用户不会看到中间状态或大量闪烁。我用它来帮助维护刷新和类似问题的排序顺序:

public void OnRefreshButtonClicked(object *sender)
{
    myListView.SuspendLayout();

    foreach (ListViewItem itm in myListView.Items)
    {
        RefreshItem(itm);
    }

    myListView.ResumeLayout();
}

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2014-02-07
    • 2020-03-09
    • 2014-06-27
    • 2021-05-10
    相关资源
    最近更新 更多