删除C#winform中的列表框项

时间:2015-04-16 23:02:51

标签: c# winforms listbox

我无法弄清楚如何在c#中正确删除winform列表框中的项目。

列表框中填充了FileSystemWatcher中的一些字符串,它基本上会在列表框中放入哪些文件被修改。

然后我做了一个“搜索”功能,删除了不包含用户在文本框中输入内容的项目。

这是代码

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

实际上我尝试过很多方法,查看各种stackoverflow问题和google结果,如:

  • 使用.RemoveAt()
  • 使用Update()代替Refresh()
  • 清除列表框并直接更新listbox.DataSource,然后刷新/更新
  • 创建一个虚拟的ListBox.ObjectCollection,对其应用搜索/删除,然后将其指定为数据源并刷新/更新。
  • 其他我不记得了

没什么可行的。列表停留在那里,调试没有帮助。

我做错了什么?

编辑:

列表框人口代码:

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

1 个答案:

答案 0 :(得分:3)

Here建议反过来删除列表项。 第一集:

listBox1.SelectionMode = SelectionMode.MultiExtended; 

然后反向删除:

for (int i = listBox1.SelectedIndices.Count-1; i >= 0; i--)
{
   listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
}
相关问题