How to: Search for an Item in a ListBox Control

In this example, you add some items to a Windows Forms ListBox control when the form is loaded. Then you search the ListBox for a specific item by clicking a button on the form. If the item is found, it is selected and a success message, which contains the item and its index, is sent by using a message box. Otherwise, an "Item not found" message is sent.

Example

private void Form1_Load(object sender, System.EventArgs e)
{
    listBox1.Items.Add("Angelina");
    listBox1.Items.Add("Isabella");
    listBox1.Items.Add("Sarah");
}

private void button1_Click(object sender, System.EventArgs e)
{
    // Set the search string:
    string myString = "Isabella";
    // Search starting from index -1:
    int index = listBox1.FindString(myString, -1);
    if (index != -1)
    {
        // Select the found item:
        listBox1.SetSelected(index,true);
        // Send a success message:
        MessageBox.Show("Found the item \"" + myString +
            "\" at index: " + index);
    }
    else 
        MessageBox.Show("Item not found.");
}

Compiling the Code

This example requires:

  • A form with a ListBox control named listBox1 and a Button control named button1. Set the button1Click event handler to button1_Click.

    Note

    This code can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

ListBox and ComboBox Controls

Visual C# Guided Tour