Search code examples
c#listviewduplicatessubitem

C# How to add an item to a listview if the item exists but the subitem is different?


I have a listview with 2 columns, and I have a button on the form where the user enters and ip:port and then it adds the item to the listview when he clicks the button, pretty basic.

What I want to do is:
when the user clicks the button, I want to check if the ip exists in the listview, and if it does, I then want to check if the port associated with that ip exists in the subitem. If it doesn't I want to add the item, that way I would have for example 2 items with the same IP, but with different ports.

Any help would be appreciated, thanks in advance!


Solution

  • Try this:

    void Main()
    {
        Form form = new Form();
    
        ListView lv = new ListView();
        lv.View = View.Details;
        lv.Columns.Add(new ColumnHeader() { Name = "ip", Text = "IP Address" });
        lv.Columns.Add(new ColumnHeader() { Name = "port", Text = "Port" });
        lv.Dock = DockStyle.Fill;
    
        // Tests.
        AddItem(lv, "10.0.0.1", String.Empty);
        AddItem(lv, "10.0.0.2", String.Empty);
        AddItem(lv, "10.0.0.1", "8080");
        AddItem(lv, "10.0.0.1", String.Empty);
        AddItem(lv, "10.0.0.1", "8080");
    
        form.Controls.Add(lv);
        form.ShowDialog();
    }
    
    private void AddItem(ListView listView, string ip, string port)
    {
        var items = listView.Items.Cast<ListViewItem>();
        // First subitem starts at index 1.
        bool exists = items.Where(item =>
            (item.Text == ip && item.SubItems[1].Text == port)).Any();
        if (!exists)
        {
            var item = new ListViewItem(ip);
            item.SubItems.Add(new ListViewItem.ListViewSubItem(item, port));
            listView.Items.Add(item);
        }
        else
        {
            Console.WriteLine("Duplicate: {0}:{1}", ip, port);
        }
    }
    

    The check is in the AddItem() method. Modify according to your requirements.