Select ComboBox or ListBox values that contain target text in C#

Select ComboBox or ListBox values

The List timezones in C# example fills a ComboBox with a list of timezones. I would like to select an initial value based on the text in the items, but I don’t want to have to select the exact text, partly because that text may change depending on Daylight Savings. At different times during the year, a timezone may have different offsets from GMT depending on whether Daylight Savings is in effect in that timezone. That means you won’t know exactly what text the program will use to represent a particular time zone.

It’s not hard to loop through a ComboBox‘s Items collection and examine each of the items to see if one contains a target string. That’s straightforward but it would be nice to use the same code to find items in ListBoxes, too.

ComboBoxes and ListBoxes are practically the same, aside from their user interfaces, so you might think this would be trivial. Unfortunately the two controls’ Items collections are not the same kinds of objects. They are ComboBox.ObjectCollection and ListBox.ObjectCollection objects. That means you can’t write a single method that takes explicitly either a ComboBox‘s or a ListBox‘s Items collection as a parameter.

Those two Items collections have different types, but they both implement the IEnumerable interface. That means you can loop through them and look at the objects they contain.

When it displays its items, a ComboBox or ListBox calls each item’s ToString method to see what text it should display. Your code can use the same technique.

The whole process is:

  1. Iterate through the objects in the IEnumerable Items collection.
  2. Use each item’s ToString method to see what text the ComboBox or ListBox will display.
  3. Use string methods to compare the value to the target value.
  4. If you find the desired match, return the object that gave the match.

The following code shows a FindItemContaining method that follows those steps.

// Select an item containing the target string.
private object FindItemContaining(IEnumerable items, string target)
{
    foreach (object item in items)
        if (item.ToString().Contains(target))
            return item;

    // Return null;
    return null;
}

The example program’s Form_Load event handler uses the following code to select the Mountain Time timezone.

cboTimeZones.SelectedItem =
    FindItemContaining(cboTimeZones.Items, "Mountain Time");
lstTimeZones.SelectedItem =
    FindItemContaining(lstTimeZones.Items, "Mountain Time");

This code calls the FindItemContaining method and sets the ComboBox‘s and ListBox‘s SelectedItem property to the item returned by the method.


Download Example   Follow me on Twitter   RSS feed


This entry was posted in controls, interfaces and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *