简体   繁体   English

C#更改标签取决于ComboBox选定的索引

[英]C# Change label depending of ComboBox Selected Index

I want to display certain value into a label depending of the item selected in the comboBox, each item in the comboBox will display a different value, problem is the comboBox has a lot of items and each one needs to display a different value 我想根据在comboBox中选择的项目在标签中显示某些值,comboBox中的每个项目都会显示不同的值,问题是comboBox有很多项目,并且每个项目都需要显示不同的值

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
   switch (comboBox.SelectedIndex)
        {
            case 0:
                if (comboBox.SelectedIndex == 0)
                {
                    Label.Text = "8";
                }
                break;
            case 1:
                if (comboBox.SelectedIndex == 1)
                {
                    Label.Text = "15";
                }
                break;
            case 2:
                if (comboBox.SelectedIndex == 2)
                {
                    Label.Text = "60";
                }
                break;
         }
}                      

How can I improve this and do it shorter? 我该如何改善它并缩短它? I was told to use an object array but how to verify which item is selected? 有人告诉我使用对象数组,但是如何验证选择了哪个项目?

This is an example of using List to make your code shorter: 这是使用列表使代码更短的示例:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        IList<string> lstString = new List<string>();
        lstString.Add("Hello");
        lstString.Add("World");
        lstString.Add("Foo");
        lstString.Add("C#");
        lstString.Add("StackOverflow");
        label1.Text = lstString[comboBox1.SelectedIndex];
    }

Since list starts at index zero and combobox starts at index zero, you can just call the index of the list to match with the index of your combobox. 由于列表从索引零开始,而组合框从索引零开始,因此您只需调用列表的索引即可与组合框的索引匹配。

You can do an initialization of your combobox.(put it on load event of form or somewhere else depends on your needs.) 您可以对组合框进行初始化(将其放置在表单的load事件或其他地方取决于您的需要。)

var listCombo = new List<int>();
listCombo.Add(8);
listCombo.Add(15);
listCombo.Add(60);
listCombo.ForEach(m =>  comboBox1.Items.Add(m.ToString()));

Then you can just assign the selected item in the label in the event code of combobox 然后,您可以在组合框的事件代码中的标签中分配选定的项目

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     label1.Text = comboBox1.SelectedItem.ToString();
}

在此处输入图片说明

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

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