通过TAG ID从列表视图中删除一行

时间:2012-12-04 20:12:53

标签: c#

如何使用行的标记ID从列表视图中删除一行?

3 个答案:

答案 0 :(得分:1)

您可以在想要删除的ListViewItem上调用ListViewItem.Remove方法。

  

此方法的功能类似于ListView控件中包含该项的ListView.ListViewItemCollection的Remove方法。您可以使用Remove方法从ListView控件中删除项目。如果要将项目移动到其他ListView控件或需要根据用户的请求删除项目以从应用程序中删除项目,此功能非常有用。

例如,您可以遍历ListViewItems中的所有ListView,查看TagRemove您要删除的项目:

// Create the ListView and ListViewItem.
ListView myList = new ListView();
ListViewItem myItem = new ListViewItem { Tag = "MyTag", Text = "My ListViewItem" };
myList.Items.Add(item);

// Look for the ListViewItem with a Tag of "MyTag" and remove it.
foreach (ListViewItem item in myList.Items) {
    if (String.CompareOrdinal(item.Tag as string, "MyTag") == 0) {
        i.Remove();
        break;
    }
}

此示例在删除第一个匹配项后退出。如果需要删除多个匹配的ListViewItems,则需要对其进行收集,然后在此之后将其删除。

答案 1 :(得分:1)

这是我做的快速功能。它利用了linq。 myTag可以是任何对象。

        string myTag = "aaa";

        List<ListViewItem> lst = listView1.Items.Cast<ListViewItem>().Where(i => i.Tag == myTag).ToList();
        if (lst.Count != 0)
        {
            listView1.Items.Remove(lst.First());
        }

答案 2 :(得分:0)

将来,您应向社区展示您在问题中投入的精力。你可以告诉我们你尝试了什么,并给我们一些例子。但是,下面是一些有助于回答您问题的代码。

int id = 0;

foreach (ListViewItem item in listView1.Items)
{
   if((int)item.Tag == id)
   {
      item.Remove();
      break;
   }
}

注意:这假定标记是整数。如果情况并非总是如此,那么您应该添加代码以防止错误。