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.


string1 causes ((value1 + value2) / 2)

string2 cuases ((value3 + value4) / 2)

string3 causes ((value5 + value6) / 2)

Im obviously new.


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...

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

        case "string3":
            // Do something...

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)

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

        // E.g.
        this.Text = selectedItemText;

Need Your Help

How to use User.Identity.Name as a parameter for SqlDataSource in ASP.NET?

c# asp.net parameter-passing sqldatasource

For SqlDataSource I can configure the external source for the incoming paramater.

How can I assign "coursecreator" role to a user in moodle?

php moodle

I write a plugin in moodle that should assign "coursecreator" role to some users.