Search code examples
stringvb.netlistboxcase-insensitive

Checking for Item in a List Box Ignoring Case


Having an issue with a bit of code designed to add an email alias to a list box. I have a check built in to ensure the item you attempt to add isn't already in the list, but the check is case sensitive when I don't want it to be. I'm not sure how to make it ignore the case... Here's my code:

Dim ItemToAdd as String = ""

ItemtoAdd = tbxItemtoAdd.Text + "@emaildomain.co.uk"

If Not lbxEmailAliases.Items.Contains(ItemtoAdd) Then
    lbxEmailAliases.Items.Add(ItemtoAdd)
End If

At the moment if the list box contains johnsmith24@emaildomain.co.uk and you try to add Johnsmith24 (capital J), it will add this successfully, but I don't want it to do that. How do I get it to ignore case?

I've tried changing lbxEmailAliases.Items.Contains(ItemtoAdd) to lbxEmailAliases.Items.Contains(ItemtoAdd, StringComparison.CurrentCultureIgnoreCase) but it's not happy with this as there are too many arguments, it will only take one.

Any ideas please?


Solution

  • If this is a standard WinForm ListBox control, then there is no way to do it without looping through all of the items and checking each one individually. For instance:

    Dim found As Boolean = False
    For Each item As Object In ListBox1.Items
        found = item.ToString().Equals(ItemToAdd, StringComparison.CurrentCultureIgnoreCase)
        If found Then
            Exit For
        End If
    Next
    If found Then
        lbxEmailAliases.Items.Add(ItemtoAdd)
    End If
    

    However, if you are comfortable with LINQ, you can do it more concisely like this:

    If ListBox1.Items.OfType(Of String).Any(Function(item) item.Equals(ItemToAdd, StringComparison.CurrentCultureIgnoreCase)) Then
        lbxEmailAliases.Items.Add(ItemtoAdd)
    End If
    

    Or, as Andy G pointed out, the LINQ Contains method is even easier since it accepts an IEqualityComparer and a stock one which supports case insensitive string comparisons is provided by the framework:

    If ListBox1.Items.OfType(Of String).Contains(ItemToAdd, StringComparer.CurrentCultureIgnoreCase) Then
        lbxEmailAliases.Items.Add(ItemtoAdd)
    End If