Search code examples
c#listboxcontainsindexoflistboxitems

How can I remove an item from a listbox without using "Contains"?


I've got this code:

for (int i = listboxWork.Items.Count-1; i > -1; i--) 
{
    if (listboxWork.Items[i].Contains(tblSent))
    {
        listboxWork.Items.RemoveAt(i);
    }
}

...which I derived from here, but my creaky old version of .NET (or maybe it's my puny version of .NET (Compact Framework) that's the problem) doesn't contain "Contains".

I reckon I could replace that line with:

if (listboxWork.Items[i].ToString().IndexOf(tblSent) > -1)

...but am not overly confident that's the best way to do it. Is there a more acceptable way?


Solution

  • Items is a collection of objects, so you need to convert the element you are working with to a string before you can use Contains:

    if (listboxWork.Items[i].ToString().Contains(tblSent))
    

    Edit: since this is CompactFramework (which I failed to recognize in the post originally, the proper solution is to use String.IndexOf, which was already identified.

    This is a perfectly acceptable mechanism, but if the CF supports it, I would strongly suggest using a case-insensitive comparison, especially if there is any user input involved in the evaluation:

    if (x.Items[0].ToString().ToLower().IndexOf(tblSent.ToLower()) != -1)