对不同的comboBox使用相同的功能

时间:2012-08-17 23:25:13

标签: c# combobox

如何更有效地完成这项工作?理想情况下,我可以在没有任何参数的情况下调用showTag,并返回正确的comboBox。

我添加了参数表来定义showTag返回的值是来自comboBox1还是comboBox2。所以,如果我想要comboBox1的值,我调用showTag(1),如果我想要comboBox2的值,我调用showTag(2)

//Return the currently selected language
public string showTag(int table)
{
    string LanguageSelection = String.Empty;
    if (table == 1)
    {
        LanguageSelection = comboBox1.SelectedItem.ToString();
    }
    else
    {
        LanguageSelection = comboBox2.SelectedItem.ToString();
    }
    string[] LanguageTag = LanguageSelection.Split(' ');
    string tag = LanguageTag[1].Replace("<", "").Replace(">", "");
    return tag;
}

1 个答案:

答案 0 :(得分:1)

你必须在你的2个组合框的同一个函数上添加一个SelectedIndexChanged事件(转到你的两个组合框的属性,点击事件和SelectedIndexChanged)

private void ComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
            ComboBox cb =  (ComboBox )sender ;
            LanguageSelection = cb.SelectedItem.ToString();
            string[] LanguageTag = LanguageSelection.Split(' ');
            //string tag have to be declared in your application at a global level
            tag = LanguageTag[1].Replace("<", "").Replace(">", "");

}