简体   繁体   中英

Deleting listbox items in C# winform

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:

  • Using .RemoveAt()
  • Using Update() instead of Refresh()
  • Clearing the listbox and updating listbox.DataSource directly, then refreshing/update
  • Make a dummy ListBox.ObjectCollection, applying the search/remove on that and then assigning it as a datasource and refreshing/update.
  • Other I don't remember

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);
    }
}

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]);
}

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