Pregunta

I have sevral text entries in a listbox, we'll call it ListBox1.

Ive been searching google, social.msdn.microsoft.com, and here. I cant figure out how to have each text entry change something when selected.

i.e

string1 causes ((value1 + value2) / 2)

string2 cuases ((value3 + value4) / 2)

string3 causes ((value5 + value6) / 2)

Im obviously new.

¿Fue útil?

Solución

You need to handle the ListBox.SelectedValueChanged event.

In main, or by using the designer, register the event handler:

listBox1.SelectedValueChanged += listBox1_SelectedValueChanged;

Then, your event handler:

void listBox1_SelectedValueChanged(object sender, EventArgs e) {
    string value = listBox1.SelectedValue as string;
    if (value == null) return;

    // What to do now?
    switch(value) {
        case "string1":
            // Do something...
            break;

        case "string2":
            // Do something...
            break;

        case "string3":
            // Do something...
            break;
    }
}

Otros consejos

You can use the SelectedIndexChanged event to execute code when items are selected. You can either test SelectedIndex or SelectedItem to see which item has been selected.

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedItems.Count == 0)
            return;

        int selectedItemIndex = listBox1.SelectedIndex;
        string selectedItemText = listBox1.SelectedItem.ToString();

        // E.g.
        this.Text = selectedItemText;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top