Share via


How to: Determine the Selected Item in a ListBox Control

This example determines which item has been selected in a Windows Forms ListBox control.

Example

private void Form1_Load(object sender, System.EventArgs e)
{
    listBox1.Items.Add("One");
    listBox1.Items.Add("Two");
    listBox1.Items.Add("Three");
}

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    if ((string)listBox1.SelectedItem == "Two")
        MessageBox.Show((string)listBox1.SelectedItem);
}

Compiling the Code

This example requires:

  • A form named Form1 with a ListBox control named listBox1. Set the Load event handler of Form1 to Form1_Load. Set the SelectedIndexChanged event handler of listBox1 to listBox1_SelectedIndexChanged.

    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