Reputation: 1
I can't figure out how to correctly remove items from winform listbox in c#.
The listbox is populated with some string from FileSystemWatcher
which basically puts in the listbox which files are modified.
Then I've made a "Search" function which remove items that doesn't contain what the user inputs in a textbox.
here's the code
private void btnSearch_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtSearch.Text) && lstFileEvents.Items.Count > 0)
{
for (int i = 0; i < lstFileEvents.Items.Count; i++)
{
if (!lstFileEvents.Items[i].ToString().Contains(txtSearch.Text))
{
lstFileEvents.Items.RemoveAt(i);
}
}
lstFileEvents.Refresh();
}
}
Actually I've tried many approaches, looking through various stackoverflow questions and google results like:
Well nothing is working. The list stays there and debugging didn't help.
What am I doing wrong?
EDIT:
listbox population code:
void fswFileWatch_Renamed(object sender, RenamedEventArgs e)
{
fswFileWatch.EnableRaisingEvents = false;
WriteListbox("Renamed: ", e);
fswFileWatch.EnableRaisingEvents = true;
}
public void WriteListbox(string msg, FileSystemEventArgs e)
{
//Some filter which works fine
if (!String.IsNullOrEmpty(txtExcludeFilter.Text))
{
foreach (string Filter in txtExcludeFilter.Text.Split(','))
{
//some other filter
if (!e.FullPath.Contains(Filter))
{
//here's where I populate the list
lstFileEvents.Items.Add(msg + e.FullPath);
}
}
}
else
{
lstFileEvents.Items.Add(msg + e.FullPath);
}
}
Upvotes: 1
Views: 1362
Reputation: 471
Here suggests removing the list items in reverse. First set:
listBox1.SelectionMode = SelectionMode.MultiExtended;
Then reverse remove:
for (int i = listBox1.SelectedIndices.Count-1; i >= 0; i--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
}
Upvotes: 4