0

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.

0

2 Answers 2

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

its giving me an error The call is ambiguous between the following methods or properties: 'Program.Form1.ListBox1_SelectedValueChanged(object, System.EventArgs)' and 'Program.Form1.ListBox1_SelectedValueChanged(object, System.EventArgs)'
I need some context to that error. What call? Are you sure you didn't accidentally define the handler method twice?
0

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.