简体   繁体   English

C#Winforms ListBox项目

[英]C# Winforms ListBox items

I have sevral text entries in a listbox , we'll call it ListBox1 . 我在listbox有几个文本条目,我们将其称为ListBox1

Ive been searching google, social.msdn.microsoft.com, and here. 我一直在搜索google,social.msdn.microsoft.com和此处。 I cant figure out how to have each text entry change something when selected. 我无法弄清楚如何在选择每个文本条目时进行更改。

ie

string1 causes ((value1 + value2) / 2) 字符串1原因((value1 + value2) / 2)

string2 cuases ((value3 + value4) / 2) string2提示((value3 + value4) / 2)

string3 causes ((value5 + value6) / 2) ((value5 + value6) / 2)原因((value5 + value6) / 2)

Im obviously new. 我显然是新来的。

You need to handle the ListBox.SelectedValueChanged event. 您需要处理ListBox.SelectedValueChanged事件。

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

You can use the SelectedIndexChanged event to execute code when items are selected. 选择项目后,可以使用SelectedIndexChanged事件执行代码。 You can either test SelectedIndex or SelectedItem to see which item has been selected. 您可以测试SelectedIndex或SelectedItem以查看已选择了哪个项目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM