Search code examples
c#winformslistboxitems

C# Winforms ListBox items


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.


Solution

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