Win窗体上的1个按钮4组合框

时间:2016-12-21 19:03:14

标签: c# winforms if-statement visual-studio-2013 combobox

我有一个按钮,它将执行一个存储过程,其中组合框中包含数据。多个if语句是我考虑每个组合框架场景的最佳方法吗?我目前有我的代码 - 这有效,但有点慢。有没有更好的方法来使用C#和VS2013编写这种语法?

private void btn1_Click()
{
    if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
    {   
        MessageBox.Show("You failed to make a selection.");
        return;
    }
    if (cbo1.Text.ToString() != "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )  
    {
        //Go route1 
    }
    if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() 1= "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )  
    {
      //Go route2 
    }
    if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() != "" && cbo4.Text.ToString() == "" )  
    {
      //Go route3 
    }
    if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" &&  cbo3.Text.ToString() == "" && cbo4.Text.ToString() != "" ) 
    {
      //Go route4 
    }
}

修改
@MethodMan - >这是你如何设置支票?

var comboBoxes =  this.Controls
              .OfType<ComboBox>()
              .Where(x => x.Name.StartsWith("comboBox"));

foreach(var cmbBox in comboBoxes)
{
  (string.IsNullOrEmpty(cmbBox.Text)) || if (cmbBox.SelectedIndex == -1)
  {
    //How to find which combobox is cmbBox
  }
}

1 个答案:

答案 0 :(得分:2)

我的建议是这样的:

private void btn1_Click()
{
int data = 0;
if(cbo1.Text.ToString() != "")
    data+=1;
if(cbo2.Text.ToString() != "")
    data+=2;
if(cbo3.Text.ToString() != "")
    data+=4;
if(cbo4.Text.ToString() != "")
    data+=8;
switch(data)
{
    case 1:
     //Go route1
    break;
    case 2:
     //Go route2
    break;
    case 4:
     //Go route3
    break;
    case 8:
     //Go route4
    break;
    default:
     MessageBox.Show("You failed to make a selection.");
    break;
}
}

我不确定它能完成你想要的工作,但速度要快得多,这样你可以检查用户选择的组合,并且他没有组合