ComboBox简化方法

时间:2015-03-30 09:05:14

标签: c# winforms visual-studio

我有3个或更多具有相同功能的ComboBox。我在想的是创建一个方法,然后调用它

以下是示例代码

问题:有没有办法将这个5 ComboBox合并为1,因为它们具有相同的功能并简化了此方法,例如我有多个ComboBoxes

    public double comboBoxTry()
    { double x;
    if (comboBox1.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox1.SelectedItem.ToString() == "Second")
    { x = 4; }

    //Second ComboBox and so on
    if (comboBox2.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox2.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox2.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox2.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox3.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox3.SelectedItem.ToString() == "Second")
    { x = 4; }

if (comboBox4.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox4.SelectedItem.ToString() == "Second")
    { x = 4; }


if (comboBox5.SelectedItem.ToString() == "First")
    { x = 3.5; }
    else if (comboBox5.SelectedItem.ToString() == "Second")
    { x = 4; }

// I want to Combine this  5 ComboBox  into 1 since  they have the same functionality 

    return x;
    }

    private void btnCompute_Click(object sender, EventArgs e)
        { txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); }

1 个答案:

答案 0 :(得分:0)

如果我理解正确,当引发事件时,你想调用comboBoxTry。

如果您正在尝试这样做,则不必这样做。您可以在EventHandle中执行此操作,在comboBox.Name上启用Switch,然后进行测试。

private void btnCompute_Click(object sender, EventArgs e)
    { 
        double x = 0;
        switch (sender.name)
        {
            case "CombOne" :
             [Your tests]
             break;
            case "Combtwo" :
            ....
            ....
        }
        txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); 
}

编辑:对于您的上次编辑,我认为您可以使用Tag属性。使用相同的行为标记所有comboBox,然后在Tag上进行测试。

你将只有

private void btnCompute_Click(object sender, EventArgs e)
        { 
            double x = 0;
            if (sender.tag == "SameBehaviorComboBox")
            {
                if (sender.SelectedItem.ToString() == "First")
                { 
                    x = 3.5; 
                }
                else if (sender.SelectedItem.ToString() == "Second")
                { 
                    x = 4; 
                }
            }
            txtResult.Text = (x * double.Parse(txtAmount.Text)).ToString(); 
    }

它适用于所有具有相同标签的comboBox。