ListView.FindItemWithText inside WHILE loop fails after first ListView line

Viewed 189

I want change the content of 2nd column of each line of ListView with diferents data according with is found via FindItemWith.

My trouble is that from of 2nd line is be overriding the previous columns, for example when i want change the content searching a text that stays on first line works fine, see:

enter image description here

Already when i want change the content searching a text that stays on second line this happens:

enter image description here

This is the code:

public void fillData(string search, string data, ListView haystack)
{
    if (haystack.Items.Count > 0)
    {
        int idx = 0;
        ListViewItem found;

        while (idx < haystack.Items.Count)
        {

            found = haystack.FindItemWithText(search, true, idx);

            if (found != null)
            {
                haystack.Items[idx].SubItems[1].Text = data.ToString();
            }

            idx++;
        }
    }
}

private void button3_Click(object sender, EventArgs e)
{
    int i = 0;

    while (i < 3)
    {

        ListViewItem item = new ListViewItem();
        item.Text = i.ToString();
        item.SubItems.Add("192.168.0." + i.ToString());

        listView1.Items.Add(item);

        i++;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    fillData("192.168.0.0", "AAA", listView1);
}

private void button2_Click(object sender, EventArgs e)
{
    fillData("192.168.0.1", "BBB", listView1);
}
1 Answers

This is because the overload function you used for FindItemWithText, keeps searching all the items from the index you passed in.

When the loop has idx = 0 then FindItemWithText will try to search all three items 0,1,2.

When the loop has idx = 1 then FindItemWithText will try to search two items 1,2.

When the loop has idx = 2 then FindItemWithText will try to search only one item 2.

So now in the first case, As you are searching for first item, your loop found it only once. But where as in second case you are searching for second item, it was found twice both (idx = 0 ---- 0,1,2) and (idx = 1 ---- 1,2) iterations. So you are updating two values both for idx=0 and idx = 1.

Here is the documentation link

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.listview.finditemwithtext?view=netframework-4.7.2#System_Windows_Forms_ListView_FindItemWithText_System_String_System_Boolean_System_Int32_

Any how FindItemWithText returns the System.Windows.Forms.ListViewItem. Just search once from zero. Use that item to update.

Related