Reputation: 83
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();
}
}
}
Upvotes: 0
Views: 466
Reputation: 168
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();
}
}
}
Upvotes: 0
Reputation: 89
Use item.Index in place of item in else section
corrected: listView1.Items[item.Index]
Upvotes: 1