0

I need to prevent Duplicate entries from ListView controller by column text. if duplicate found I need to get the ListView Item for further process. I saw every one says

ListViewItem item = ListView3.FindItemWithText("test");
if (!listView1.Items.ContainsKey(txt))
{
    // doesn't exist, add it
}

but how can I point which Column text?? I did prevent duplicates by adding ids into a array and after check array value exists. but in that case I can find which entry duplicated.

this is my code.

rd = cmd.ExecuteReader();

// Validation not working - duplicating ListviewItems
while (rd.Read()) {
    ListViewItem lvvi = new ListViewItem(rd.GetString(0));
    lvvi.SubItems.Add(rd.GetString(1));
    lvvi.SubItems.Add(rd.GetString(5));
    lvvi.SubItems.Add("1");
    lvvi.SubItems.Add(rd.GetString(0));

    int listViewItemID;

    int[] ids;
    ids = new int[100];
    if (listView3.Items.Count > 0)
    {
        int addingItemID;
       //ADD ListView ids into array
        int i=0;
        foreach (ListViewItem li in listView3.Items)
        {
            listViewItemID = Int32.Parse(li.SubItems[0].Text);
            addingItemID = Int32.Parse(rd.GetString(0));
            ids[i] = listViewItemID;
            i++;
        }

        //Check item allready exsist
        if (ids.Contains(Int32.Parse(rd.GetString(0))))
        {

            MessageBox.Show("sdsd");
        }
        else {
            listView3.Items.Add(lvvi);
        }



    }
    else {

        listView3.Items.Add(lvvi);
    }



}

//Calculate Price summery
this.calculatePrice();
Damian
  • 2,752
  • 1
  • 29
  • 28
user3722956
  • 59
  • 2
  • 13
  • if you can use Linq, this might help: http://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property – ADyson Dec 21 '16 at 09:44

1 Answers1

0

Instead of looping to get all id's, you can loop through the items or use linq to find the specific id and keep the result. This can be done in an external function or by replacing the ids portion with the loop or use something like FirstOrDefault:

addingItemID = rd.GetString(0);
ListViewItem existing = listView3.Items.Cast<ListViewItem>().FirstOrDefault(li => li.SubItems[0].Text == addingItemID); //(not sure if the cast is needed)

if (existing != null)
{
    //item exists, variable existing refers to the item
    MessageBox.Show("sdsd");
}
else 
{
    listView3.Items.Add(lvvi);
}
Me.Name
  • 12,259
  • 3
  • 31
  • 48