简体   繁体   中英

How to remove selected rows from a listView

I want to remove rows from a listview after checking for a particular string. If the string in the textbox matches the string in the listview, the row remains, otherwise the row is remove. The 2 foreach loop and the top part of the if statement works fine, however the else section is what giving me problem.... I am not sure how to code it.

Thanks in advance

code so far:-

foreach (ListViewItem item in listView1.Items)
{
    foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
    {
        if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
        {
            var index = item.Index;
            MessageBox.Show(listView1.Items[index].ToString());
            count++;
        }
        else
        {
            listView1.Items[item].Remove();
        }               
    }   
}        

Use item.Index in place of item in else section

corrected: listView1.Items[item.Index]

You Can Add Matched Items in new List instead removing Items form current loop like that :-

        listView1.Items newItemList = new listView1.Items();
        foreach (ListViewItem item in listView1.Items)
        {
            foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
            {
                if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower()))
                {
                    var index = item.Index;
                    MessageBox.Show(listView1.Items[index].ToString());
                    count++;

                    newItemList.Add(item); 

                }
                else
                {
                    //listView1.Items[item].Remove(); 
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM