zoukankan      html  css  js  c++  java
  • How do I Check for Duplicate Items in a ListView?

    This How To was written in response to the following question in the C# Corner Forums about ListViews:

    The user states:

    Question: "I have code which I used to check duplication in a ListView, but it doesn't seem to be working. Here is my situation. I have three columns in a ListView and I want to check to make sure that I don't duplicate a field when I add an item to the ListView. How do I do that?"

    I tried this code, but it doesn't seem to work:

    if (listView1.Items.Contains(lvi) == false)
    {
    //Add the item to the ListView Control
    listView1.Items.Add(lvi);
    }
    else
    {
    //Warn user of duplicate entry...
    MessageBox.Show("Duplicate Item!");
    }

    Answer:
    This will not work because you are probably not passing the exact same object, but an object that contains the same text. Is this the situation?
    For example this works fine with your code:

    ListViewItem lvi = new ListViewItem("dog");
    Add(lvi);
    Add(lvi);

    The second time you try to add the same object, you get the message box.
    If you want to check the internal information in the row against your Add, you can provide a key in your item. The key corresponds to the name of the item and can be used to compare items using the ContainsKey method:

    if (!listView1.Items.ContainsKey(lvi.Name))
    {
    //Add the item to the ListView Control
    listView1.Items.Add(lvi);
    }
    else
    {
    //Warn user of duplicate entry...
    MessageBox.Show("Duplicate Item!");
    }

    This will work for the following code with a unique name for your ListViewItem (the unique name being "item1"):

    ListViewItem lvi1 = new ListViewItem("dog");
    lvi1.Name = "item1";
    Add(lvi1);

    Otherwise, if you don't provide a key, you'll need to compare the list of items and check each subitem within each item:

    private bool IsInCollection(ListViewItem lvi)
    {
    foreach (ListViewItem item in listView1.Items)
    {
    bool subItemEqualFlag = true;
    for (int i = 0; i < item.SubItems.Count; i++)
    {
    string sub1 = item.SubItems[i].Text;
    string sub2 = lvi.SubItems[i].Text;
    if (sub1 != sub2)
    {
    subItemEqualFlag = false;
    }
    }
    if (subItemEqualFlag)
    return true;
    }

    return false;

    }

    版权说明:作者:张颖希PocketZ's Blog
    出处:http://www.cnblogs.com/PocketZ
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    若本文为翻译内容,目的为练习英文水平,如有雷同,纯属意外!有不妥之处,欢迎拍砖

  • 相关阅读:
    kgtp
    SSIS高级转换任务—行计数
    SSIS高级转换任务—OLE DB命令
    SQL点滴16—SQL分页语句总结
    Windows7中使用Task Scheduler调用WinScp批处理实现上传下载文件
    SSIS高级转换任务—导入列
    SSIS高级转换任务—关键词抽取
    SQL点滴15—在SQL Server 2008中调用C#程序
    C# 文件操作 全收录 追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件....
    SQL点滴18—SqlServer中的merge操作,相当地风骚
  • 原文地址:https://www.cnblogs.com/PocketZ/p/2122648.html
Copyright © 2011-2022 走看看