Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.
See Also
Concepts
Designing a User Interface in Visual C#