Monday, April 21, 2014

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 01:

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

1 comment:

  1. Could you please difference between FindString & FindStringExact Methods of Lists in .net?

    ReplyDelete